-3

We had a class where professor asked us to overload ostream to print object this way (saying we have object t)

cout << t << endl;

Then we were asked to cout the same object this way

t << cout << endl;

How does this work and why?

ostream& operator<<(ostream& o, T& t)
{
   return o << t.member;
}

// This is usual way and "normal" that I know about but won't work on both ways

Expected output is the same, but second way is confusing. Why would anyone want to use it?

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56

1 Answers1

4

As any good book or tutorial should tell you, for any operator X the expression a X b will (if a suitable overload is found) be equal to operatorX(a, b).

Or if a (in a X b) have overloaded the operator as a member function, then it's equal to a.operatorX(b).

If we now take cout << t, that will call either operator<<(cout, t) or cout.operator<<(t) depending on the type of t.

As should be easy to guess, reversing the order to t << cout would then be operator<<(t, cout) or t.operator<<(cout).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621