I've been tinkering around with classes and operator overloading in C++ - and recently I came across a code in which both
cout << class_object
and
class_object << cout
works if I overload the '<<' operator (to return individual class members).My class has a member int num, and the member function
ostream& operator << (ostream& os)
{
os << num;
return os;
}
The following function is defined outside the class -
ostream& operator<<(ostream& os, X &class_object)
{
return class_object << os ;
}
(supposing X is the class)
Any idea why it works? I can't seem to figure it out. Also, why are the TWO function definitions necessary for << (one outside the class, and one inside)? Any way to make it work without that? I'd love some closure on the whys and hows of its working, if you don't mind.