What good are public variables then?

后端 未结 14 2120
悲哀的现实
悲哀的现实 2020-12-09 15:16

I\'m a total newbie with tons of ?\'s in my mind and a lot to experience with C++ yet! There\'s been something which I find really confusing and it\'s the use of public vari

14条回答
  •  囚心锁ツ
    2020-12-09 15:39

    I agree, in part, with the other answers regarding the use of getter and setter methods to allow for future changes but there is still a fundamental problem, you are exposing the internal data of your object for other objects to modify.

    It is better to ask the object to perform some action on the data it holds, via a method, rather than treat the object as a collection of values.

    Here's an interesting article on Why Getter and Setter Methods are Evil, it's written with Java in mind but the same applies to C++.

提交回复
热议问题