According to Can't Overload operator<< as member function
When overloaded as a member function, a << b is interpreted as a.operator<<(b), so it only takes one explicit parameter (with this as a hidden parameter).
Since this requires that the overload be part of the class used as the left-hand operand, it's not useful with normal ostreams and such. It would require that your overload be part of the ostream class, not part of your class. Since you're not allowed to modify ostream class, you can't do that. That leaves only the global overload as an alternative.
I know that for example:
friend std::ostream& operator<< (std::ostream &out, const Obj &obj);
acts like a function that takes an object of ostream and some object that you are trying to print and then returns an ostream object.
But I don't understand how doing cout << obj
will call this function.
Wouldn't cout << obj
do something like cout.operator<<(obj)
, which is exactly what we don't want? So why does it actually call the function? And why does it allow the return value to go back to cout
?
EDIT:
I had read over What are the basic rules and idioms for operator overloading? previously and it states
"A binary infix operator @, applied to the objects x and y, is called either as operator@(x,y) or as x.operator@(y).4"
which provides some further clarity, but I don't see how it answers my question.