user990689
user990689

Reputation: 13

Returning by reference versus by value. C++

In what situation would generate an error if you don't return something by reference for a function?

Upvotes: 0

Views: 137

Answers (3)

Alok Save
Alok Save

Reputation: 206518

In what situation would generate an error if you don't return something by reference for a function?

Restricting the answer to what is being exactly asked,
Whenever you want the return value of the function to act as an l-value, and you do not return by reference then it will generate an error.

The more common example of this is overloading the operator [](the array subscription operator), You have to return by reference in order to use the [] on the l.h.s or more correctly to use it as an l-value.

An example:

class Myclass 
{ 
     int i;
     public:
     /*Not returned by reference- gives error*/
     int operator[](int idx){ return i;}

     /*Returned by reference- gives no error*/
     //int& operator[](int idx){ return i;}
};

int main()
{
   Myclass  obj;
   obj[1]= 10;
   return 0;
}

Output:

prog.cpp: In function ‘int main()’:
prog.cpp:16: error: lvalue required as left operand of assignment

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258568

The question should be when is it not safe to return by reference. Whenever you return a variable local to a method by reference, you're invoking undefined behavior.

It's unsafe to return by value when you haven't correctly implemented the copy constructor.

You'd get an error if copy constructor was declared private and you'd try to return by value.

Upvotes: 2

James Kanze
James Kanze

Reputation: 153909

The default action should be to return by value. The main case where you'ld want to return a reference is when you want to expose some “part” of a larger object; e.g. an element in a vector or a map. The important thing is that the object referred to must have a lifetime beyond that of the calling function.

Upvotes: 2

Related Questions