tags:

views:

193

answers:

3

Can anybody explain why do you need to return a reference while overloading operators e.g.

friend std::ostream& operator<< (std::ostream& out, const std::string& str)
+7  A: 

It is to make "chaining" of the operator work, in examples like this:

std::cout << "hello," << " world";

If the first (leftmost) use of the operator<<() hadn't returned a reference, there would not be an object to call for the second use of the operator.

unwind
+1 Beat me to it
Andy White
heh :) the "beat me to it" problem is so awful, esp on crowded communities like SO
Here Be Wolves
+4  A: 

It's for operator chaining (if you return a pointer, you have to dereference it) and for not make a potentially huge and expensive copy of an object (in the case you return a value), if it is even possible to do so.

akappa
... if you can even perform a copy of the object received. What should a copy of std::cout be?
David Rodríguez - dribeas
+3  A: 

A general rule, stated by Scott Meyers in Effective C++, is that when in doubt, "do as the ints do". So for example, operator= should return a reference so code like this works:

MyClass A, B, C;
A = B = C = 0;
rlbond