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.
        O       o                      .oOOOo.  
o O o .oOOo. .oOOo. o o
O o O O O.
o o o o `OOoo.
.oOo. o O O O' O' `O
OooO' O O o O O o
O `o Oo O .O .O O. .O
`OoO' `OoooO'O o' oOoOoO oOoOoO `oooO'

Enter the code depicted in ASCII art style.