Search code examples
c++operator-overloadingreturn-typeostream

Why is the return type reference to output stream?


I am new to C++ and learning operator overloading. Now in the followng code, I get everything except little bit confused as to why the return type is reference to output stream?

We have the following enum.

enum days{ SON, SAT, MON, TUE, WED, THRUS, FRI };

And we are overloading << operator , to print the days instead of the numerical value 0, 1, 2 ... and so on.

The code is:

ostream& operator <<(ostream &,const days &d)
{
 switch(d)
 {
  case SUN: out << "SUN"; break;
  case MON: out << "MON"; break;
  case TUE: out << "TUE"; break;
  case WED: out << "WED"; break;
  .....
  ... 
 }
 return out;
} 

Solution

  • ostream class has overloaded the insertion operator (<<) for many types of data; int, char, char*, string...

    • the return type of this operator is a reference to an ostream object so when you call it; you can use the return type to print another stuff and the return type of printing this stuff is a reference to an ostream object which you can use it to print another stuff and so on...

    • when you write:

      cout << 1 << "Hello" << 2.7 << endl;
      

    at the beginning cout prints 1 and returns us an ostream object we use it to print "Hello" (calling <<(ostream&, char*)) and returns again a reference to an ostream object so we use it to print 2.7 and so on...

    • the line above can be translated as:

      (((cout << 1) << "Hello") << 2.7) << endl;