What do you mean by ‘Return by Reference’ in C++ ?

 
 

A function can be declared to return a pointer or a reference. When the function is returning a reference, the calling function receives the lvalue for the variable. The calling function can then modify the variable or take its address.
If the return value is a large class object, using a reference (or pointer) return type is more efficient than returning the class object by value. In some cases, the compiler can automatically transform a return by value to a return by reference.
E.g.

Complex& compute (Complex c)
{
Complex *tmp = new Complex ();
// …
return tmp;
}However care should be exercised when returning a reference to a local object. The lifetime of the local object terminates with the termination of the function. The reference is left aliasing undefined memory after the function terminates.

Nez

is it not "return *tmp;"? (ref rather than ptr)
I doubt usefullness of this construct. By using ptr instead you state that result is now owned by caller and is less confusing.
The answer to orig question b.t.w. could relate more to returning value in reference-declared call argument....

  1. //retcode=0 if successful, result is stored in argument
  2. //...by reference (should be clarified by interviewer IMHO)
  3. int compute(const Complex& c1, int i2, Complex& result) {
  4. if (i2 == 0) return -1;
  5. result = c1 * 2 / i2;
  6. return 0;
  7. }

 
 

Nez

Ok, there is such thing. Mostly used to lvalue the global objects. This is a very bad code but it gives the point;
====

  1. int globalbuff[100];
  2.  
  3. class Deca {
  4. public:
  5. Deca(int daInit) : m_iStart(daInit) {};
  6. int& Elem(int iOff) {
  7. return globalbuff[m_iStart + iOff];
  8. }
  9.  
  10. private:
  11. int m_iStart;
  12. };
  13.  
  14.  
  15. void main(void) {
  16. Deca daDec2(22);
  17.  
  18. daDec2.Elem(10) = 20; //inits globalbuff[32] with (int) 20
  19. }