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
{
    public:
        friend std::ostream& operator<< (std::ostream& o, const A& a);
        ...
 
    private:
        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.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
 Oo      oO           o       Oo      oO  O       o  `o    O  
O O o o o O O O O o o o O o O
o o O O O o o o o O O O o O O
O Oo O o o o O Oo O o o oOo
O o OooOOo O O o o O o o
o O O O o O O O O O
o O o o . o O `o Oo o o
O o O OOoOooO O o `OoooO'O O O

Enter the code depicted in ASCII art style.