0

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.

Caife
  • 415
  • 1
  • 5
  • 16

1 Answers1

0

The member function makes class_object << cout; work, because member functions have a pointer to the object as first implicit parameter. This is wrong because it is counter-intuitive in C++.

Following code:

ostream& operator<<(ostream& os, X &class_object)
{
   return class_object << os;
}

makes use of the "inverted" member operator overload and inverts it again, so now operator<< works in both directions for your class.

The only reasonable code is:

ostream& operator<<(ostream& os, X &class_object)
{
   os << class_object.num;
   return os;
}
stefaanv
  • 14,072
  • 2
  • 31
  • 53
  • There had been a mistake in my second function. Edited it now. – Caife Jul 02 '13 at 06:52
  • It doesn't change a lot in my result: "Don't use member operator overload and hence, don't call it from the free operator overload." – stefaanv Jul 02 '13 at 09:44