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