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
In this case the difference is that returning by reference allows caller to modify the data member by assigning value to it, while returning by value returns caller only a copy of the variable.
First allows you to write:
myObj.GetVal() = 100;
While the latter doesn't.
Note that the first in a way allows caller of the function to obtain a reference to a private
data member and they can modify it at will. For me this is something which i like to avoid. I do not want users of my class to change the state of my class members at their will.