Thursday, April 21, 2011

What is the importance of returning reference in operator overloading

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)
From stackoverflow
  • 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.

    Andy White : +1 Beat me to it
    Here Be Wolves : heh :) the "beat me to it" problem is so awful, esp on crowded communities like SO
  • 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.

    David Rodríguez - dribeas : ... if you can even perform a copy of the object received. What should a copy of std::cout be?
  • 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;
    

0 comments:

Post a Comment