You are here:

C++/Reference operator

Advertisement


Question
Hi ,
      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

Answer
Functions 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

};  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.