C++/Reference operator
Expert: vijayan - 10/20/2009
QuestionHi ,
Can you please tell me "importance of returning reference in operator overloading ? with example"
what happpen if dont use the refernece operator in this case
Many thanks in Advance
AnswerFunctions can be declared to return a reference type. There are two reasons to make such a declaration.
1. Efficiency: if the object is expensive to copy, returning a reference to an object is more efficient, making a copy of the object can be avoided.
2. Convenience: the call to the function can be used as an l-value.
There are situations where a function should not return an object by reference. For instance, you should not return a dangling reference - a references to a local, nonstatic object defined inside the function.
see:
http://codeidol.com/cpp/effective-cpp/Designs-and-Declarations/Item-21-Dont-try-...
example:
class Rational
{
public:
Rational( int numerator = 0, int denominator = 1 ) ;
Rational operator+ ( const Rational& that ) ; // return by value
Rational& operator+= ( const Rational& that ) ; // return by reference
// ...
private: int n, d ; // numerator and denominator
};