Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between returning reference vs returning value C++

Tags:

c++

reference

Question about why is it necessary at all to return a reference from a function.

Following code behaves exactly the same, if we replace int& with int in line9 and line16.

Is it true in my example code, returning reference vs value doesnt matter? In what kind of example it will start to matter?

In my mind, we cant return the reference of a local variable of the function, since the local variable will be out of scope for the caller. Therefore, it only make sense to return a reference of a variable that the caller can see (in scope), but if the caller of the function can see the variable, then it doesnt need to be returned(?) (or is this returning done for the sake of keeping the code neat and tidy?)

Related link: Is returning a reference ever a good idea?

#include <iostream>
using namespace std;

class myClass{
private:
    int val;
public:
    myClass(int);
    int& GetVal();
};

myClass::myClass(int x){
    val = x;
}

int& myClass::GetVal(){
    return val;
}

int main()
{
    myClass myObj(666);
    cout << myObj.GetVal() << endl;
    system("pause");
    return 0;
}
like image 405
Sida Zhou Avatar asked Dec 27 '22 06:12

Sida Zhou


1 Answers

The difference is that, when you return a reference, you can assign to the result of GetVal():

myObj.GetVal() = 42;

You can also keep the returned reference around, and use it to modify myObj.val later.

If GetVal() were to return val by value, none of this would be possible.

Whether any of this is desirable, or indeed good design, is a different question altogether.

Note that your example is very different to the code in the linked question -- that code returns an invalid reference and is unequivocally a bad idea.

like image 123
NPE Avatar answered May 13 '23 04:05

NPE