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;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…