Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ostream << overloading confusion

Tags:

c++

stream

When you're overloading the << operator for a class (pretend this is defined as a friend in SomeClass), why do you both take a reference to the ostream and return that ostream?

ostream& operator<<(ostream& s, const SomeClass& c) {
    //whatever
    return s;
}

What benefit can returning the ostream be when it was already directly modifiable by reference? This seems redundant to me - though I'm sure it's not :)

like image 745
John Humphreys Avatar asked Dec 10 '22 06:12

John Humphreys


2 Answers

It allows to "chain" output together. As in :

std::cout << someObj << someValue;

This is equivalent to something like :

operator<<(operator<<(std::cout, someObj), someValue);
like image 123
Sander De Dycker Avatar answered Dec 27 '22 01:12

Sander De Dycker


This is not redundant, but useful for chaining calls. It's easier to see with functions like std::string::append, so I'll start with that:

std::string mystring("first");
mystring.append(" second");
mystring.append(" third");

can be rewritten as:

std::string mystring("first").append(" second").append(" third");

This is possible because .append() returns a reference to the string it modified, so we can keep adding .append(...) to the end. The code correlating to what you are doing is changing from this:

std::cout << "first";
std::cout << " second";
std::cout << " third";

into this. Since operator<< returns the stream, we can also chain these!

std::cout << "first" << " second" << " third";

see the similarity, and usefulness?

like image 44
Mooing Duck Avatar answered Dec 27 '22 02:12

Mooing Duck