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.OOOo.    OoooOOoO                         o       O 
O `o o OooOOo O o
o O O o `o O'
O o o O O o
o O O ooOOo. o O `OoOo. `O'
O o o O OoO o o
o .O' O o o o O O
OooOO' OOooOooO `OooO' O O o O

Enter the code depicted in ASCII art style.