Difference between returning reference vs returning value C++

前端 未结 3 1913
长发绾君心
长发绾君心 2020-12-02 01:29

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

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 01:50

    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.

提交回复
热议问题