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
  • 7
  • Where would you want to use `const`? – Yksisarvinen Jul 07 '20 at 09:44
  • 2
    @Yksisarvinen This was asked earlier, the OP wants to write `friend const ostream& operator<<(const ostream&, const className&);` so that can pass temporary `ostream` objects to `operator<<` I did try to explain the reason, though obviously not very well. – john Jul 07 '20 at 09:46
  • @joh do feel free to mark this as a duplicate – Aykhan Hagverdili Jul 07 '20 at 09:48
  • 2
    @_Static_assert No it's not a duplicate. The issue came up as an aside to a different question. – john Jul 07 '20 at 09:49

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.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
  • 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_an_ai
  • 109,796
  • 11
  • 89
  • 185