Difference between returning reference vs returning value C++ -
question why necessary @ return reference function.
following code behaves same, if replace int& int in line9 , line16.
is true in example code, returning reference vs value doesnt matter? in kind of example start matter?
in mind, cant return reference of local variable of function, since local variable out of scope caller. therefore, make sense return reference of variable caller can see (in scope), if caller of function can see variable, doesnt need returned(?) (or returning done sake of keeping code neat , tidy?)
related link: is returning reference ever 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; }
the difference that, when return reference, can assign result of getval():
myobj.getval() = 42; you can keep returned reference around, , use modify myobj.val later.
if getval() return val value, none of possible.
whether of desirable, or indeed design, different question altogether.
note example different code in linked question -- code returns invalid reference , unequivocally bad idea.
Comments
Post a Comment