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.
_up_rmarket: