Moule Lin
← All notes

Overloading cout as a Global Function

Why are stream operators overloaded with friend functions in C++

As a member function, the left operand must be the object itself

In cout << XXX, it is cout that calls operator<<, not XXX.
If you make operator<< a member function, you can only use the form XXX << cout.

So this also works; it just goes against convention

struct point
{
    int x;
    int y;

    point (int _x, int _y)
        : x(_x), y(_y)
    {}

    std::ostream& operator<<(std::ostream& os) const
    {
        os << "(" << x << ", " << y << ")";
        return os;
    }
};

int main(int argc, const char* argv[])
{
    point p1(1, 2);

    p1 << std::cout; // equivalent to p1.operator<<(std::cout);

    return 0;
}