C++: Friend Functions
Friend functions are functions that a class permits
to use the class's private members. This is commonly done
to overload binary operators that have another class as the
left operand, eg <<. Another use is to make some
function calls more attractive. For example,
Time t1, t2;
. . .
if (t1.compareTo(t2) == 0) . . .
Might be more attractively written as
if (compareTo(t1, t2) == 0) . . .
Because compareTo needs to examine the private values in t1 and t2,
this second form is only possible if the class declares that
compareTo is a friend.
Another use of friend functions is to permit operators to be
commutative. For example x+i normally will mean the same
thing as i+x, but if x is an object and i is an int, the
first can be written as a member function and the second only
as a friend function.
A final reason for member functions is efficiency since
they can access the private members directly they can avoid some
of the costs of going thru functions.
Put friend declarations before public and private
A class doesn't control the scope of friend functions so
friend function declarations are usually written at the
beginning of a .h file. Public and private don't apply to them.
Example - redefine << to allow Points to use cout
//=== Point.h file =============================
class Point {
friend ostream& operator<<(ostream& output, const Point p);
public:
Point();
Point(int x1, int y1)
. . .
//=== Point.cpp file ===========================
. . .
ostream& operator<<(ostream& output, const Point p) {
output << "(" << p.x << ", " << p.y <<")";
return output; // make sure it can be used for more output
}
. . .