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

前端 未结 5 1767
[愿得一人]
[愿得一人] 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 02:13

    I am able to access the private member variable outside the class scope

    If you are referring to the x in main() then that is different from the x declared in class foo. If you try to access the obj.x then the compiler will definitely complain.

    Is it a bad practice to receive a returned private variable by reference ?

    There is nothing wrong in "receiving" the reference to a private member. But giving out the reference to a private member makes declaring it private useless. By declaring a variable to be a private member you restrict the access to that member only to the class' methods.

    regarding this method, what does the return type convey ? And also when should I have return type of this kind ?

    Not sure as to which method you are referring to?!?!?!

提交回复
热议问题