Why can I expose private members when I return a reference from a public member function?

前端 未结 5 1764
[愿得一人]
[愿得一人] 2021-02-02 01:21

In the code snippet, I am able to access the private member variable outside the class scope. Though this should never be done, why is it allowed in this case? Is it a bad pract

5条回答
  •  南笙
    南笙 (楼主)
    2021-02-02 01:57

    Like Donotalo said, it is perfectly valid. The idea of having private members is to disallow other classes/functions to access the private member of the class without your permission. If you are happy to make a function to allow other classes/functions to access your private members, the compiler has nothing against that really :-)

    Usually, it is useful to have a private member and have a get function to allow other classes/functions to get the value of the function, but only the class will be able to change it.

提交回复
热议问题