Skip to main content

Overloading << for a custom class

Posted in

Q: Why overload << operator outside your own class and then make it its friend? Why not make it a member?

A: Well, you can make it a member of your class, but if you do, you are condemned to use it as

YourClass a;
a << cout;

Which is not very nice. We would rather prefer a usual

YourClass a;
cout << a;

That's why we do this (or, in fact, we have to do this)

class A
        friend std::ostream& operator<< (std::ostream& o, const A& a);
        int mI;
std::ostream& operator<< (std::ostream& o, const A& a)
   return o << a.mI;

Post new comment

The content of this field is kept private and will not be shown publicly.
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
 .oOOOo.                         o      'O           
o o O o
O. o O
`OOoo. o o
`O o O `OoOo. .oOo O O' `oOOoOO.
o OoO o O `o o O o o
O. .O o o O o `o O o O O
`oooO' O O o `OoO' `o' O o o

Enter the code depicted in ASCII art style.