C++: OOP: Overloading << and >>
Perhaps the most common use of friend functions is
overloading << for I/O.
This example overloads << (ie, defines a operator<<
function)
so that Point
objects
can use cout
and <<.
// example usage
Point p;
. . .
cout << p; // not legal without << friend function.
Declare before public
and private
in header file
Declare friend functions outside the public
and private
sections of the header file. Often they are placed first as in the
example below.
//=== Point.h file =============================
class Point {
friend ostream& operator<<(ostream& output, const Point& p);
public:
. . .
private:
. . .
Definition
The definition of the operator<<
function can be in any file.
It is not a member
function, so it is defined with two explicit operands. The operator<<
function
must return the value of the left operand (the ostream
) so that multiple <<
operators may be used in the same statement.
Note that operator<<
for your type can be defined in terms of
<<
on other types, specifically the types of the data
members of your class (eg, ints x and y in the Point class).
//=== Point.cpp file ===========================
. . .
ostream& operator<<(ostream& output, const Point& p) {
output << "(" << p.x << ", " << p.y <<")";
return output; // for multiple << operators.
}
Notational practice
The following are identical.
First using traditional operator notation.
Point p, q;
cout << p << q;
This can be written with parentheses to show the order of evaluation.
This makes it clearer that the first operation has a result that
is used by the second output operation.
((cout << p) << q);
An equivalent way is to write this using function for <<
is
operator<<(operator<<(cout, p), q);
Friend functions are not always needed
If there is no need to reference private data members, operator<<
doesn't need to be a friend
function; it can be
a function that isn't associated with the class in any way.
Defining >> for input
>>
can be defined in a similar way.