S
subramanian100in
Stroustrup, in his book TC++PL 3rd Edition, in page 16, under the
section '1.8 Advice' has mentioned the following:
[2] [a] Don't use global data(use members)
Don't use global functions
[c] Don't use public data members.
[d] Don't use friends, except to avoid [a] or [c].
Consider the following scenarios:
Scenario 1:
----------------
class Test
{
friend ostream & operator<<(ostream &os, const Test &ref);
}
Here the friend ostream &operator<<() can be avoided by providing a
Test:rint_output() function and expect the user to explicitly call
Test_obj.print_output(os) for an object Test_obj of type Test.
Scenario 2:
----------------
class Test
{
friend Test operator+(const Test &arg1, const Test &arg2);
}
This friend function can be avoided as follows:
class Test
{
Test &operator+=(const Test &ref);
}
Test operator+(const Test &arg1, const &arg2)
{
Test temp(arg1);
return temp += arg2;
}
Scenario 3:
----------------
Consider invert(m) for inverting a 'Matrix m' to the alternative
m.invert()
By providing Matrix::invert(), here also the friend function can be
avoided.
I want to know if there are some guidelines and examples where the
need for using a friend function is unavoidable.
Kindly explain.
Thanks
V.Subramanian
section '1.8 Advice' has mentioned the following:
[2] [a] Don't use global data(use members)
Don't use global functions
[c] Don't use public data members.
[d] Don't use friends, except to avoid [a] or [c].
Consider the following scenarios:
Scenario 1:
----------------
class Test
{
friend ostream & operator<<(ostream &os, const Test &ref);
}
Here the friend ostream &operator<<() can be avoided by providing a
Test:rint_output() function and expect the user to explicitly call
Test_obj.print_output(os) for an object Test_obj of type Test.
Scenario 2:
----------------
class Test
{
friend Test operator+(const Test &arg1, const Test &arg2);
}
This friend function can be avoided as follows:
class Test
{
Test &operator+=(const Test &ref);
}
Test operator+(const Test &arg1, const &arg2)
{
Test temp(arg1);
return temp += arg2;
}
Scenario 3:
----------------
Consider invert(m) for inverting a 'Matrix m' to the alternative
m.invert()
By providing Matrix::invert(), here also the friend function can be
avoided.
I want to know if there are some guidelines and examples where the
need for using a friend function is unavoidable.
Kindly explain.
Thanks
V.Subramanian