0

The prototype of operator function to overload << operator is:

friend ostream& operator<<(ostream&, const className&);

I am a newbee so it would be appreciated if it could get explained with simple examples. Thanks

Bilal Sheikh
  • 119
  • 6

2 Answers2

1

The act of writing to an object of type ostream can change its state. For instance, could set the fail bit or any other fail state. For that reason, the function parameter is a reference to non-const.

Ayxan Haqverdili
  • 23,309
  • 5
  • 37
  • 74
  • 2
    Not to mention that conceptually writing to a stream is not const, since it changes the environment, such as the file position for an fstream. – john Jul 07 '20 at 09:48
1

Typically, when you write

foo f;
std::cout << f;

you ignore the returned value. Remember that calling operators is similar to calling methods and the same line can be written as:

operator<<(std::cout,f);

For the argument type, consider that writing something to a stream does modify internal state of the stream. Hence, operator<< takes a non-const reference. You cannot pass a const object/reference, because a constant stream would not allow anything to be inserted.

Now chaining:

foo f,g;
std::cout << f << g;

same as

operator<<( operator<<( std::cout,f) , g);
            ------------------------
                     |
                     v
             returns non-const ref

If operator<< would return a constant reference you could not chain it.

463035818_is_not_a_number
  • 88,680
  • 9
  • 76
  • 150