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
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
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.
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.