What are the purposes of having private/protected members of a class/structure in object-oriented programming? What's the harm in having all members be public?
相关问题
- how to define constructor for Python's new Nam
- Keeping track of variable instances
- What uses more memory in c++? An 2 ints or 2 funct
- Object.create() bug?
- How Does WebSphere Choose the Classloading Order i
相关文章
- 接口B继承接口A,但是又不添加新的方法。这样有什么意义吗?
- Should client-server code be written in one “proje
- Algorithm for maximizing coverage of rectangular a
- Private static variables in php class
- NameError: name 'self' is not defined, eve
- Is there an existing solution for these particular
- Implementation Strategies for Object Orientation
- .NET - how to make a class such that only one othe
Sometime you don't want to reveal private information to everybody. E.g you don't want to let your age be known to public but you may want tell people if you are above 25.
Metaphorically, exposing private members as public is like having an option on your car's dashboard that allows you to tweak the engine oil pressure.
The car should manage that internally (privately), and the user should be shielded from messing with it directly (encapsulation), for obvious reasons.
What are the purposes of having inner organs in the human body? What's the harm in having all organs outside?
Exactly!
The short answer would be: Because you need them so you can't live without them and you can't expose them to everyone to modify and play around with them because that could kill you (cause your class not to function properly).
Nicely explained in Section 7.4: Protect your Private Parts of this online C++ tutorial.
The above explanation explains how using
private
eases the learning curve. Here's an example which explains the "code breaking" aspect:Here's a class
ParameterIO
which reads and writes a vector of integer parametersThe following code breaks this class: