First, let's take a look at why the member variables should not be public. Then let's take a look at all arguments against the Public member variables that apply to the protected member variables as well. Finally, we can conclude that all member variables should be private.
1. Syntax consistency. If the member variables are not public, all access member variables become functions, so there is no issue of parentheses.
2. Using member functions gives you more precise control over member variables. Therefore, you can design "no access (no function corresponding to this member is written)", "read-only access (const)", and "read/write access ".
3. encapsulation. If you use a function to access a member variable, when you want to replace the Member variable with a certain calculation in the future, the class customers do not know that the internal implementation of the class has changed.
Encapsulation of member variables and damage caused by changes in the content of member variablesCodeThe quantity is inversely proportional. The so-called change may be to remove it from the class.
Suppose we have a public member variable, and we have to cancel it. How much code will be destroyed?
All code that uses it will be destroyed, so the public member variables are completely unencapsulated. Suppose it is a protected variable? All subclasses that use it will be destroyed.
Remember:
- Remember to declare the member variables as private. This allows the customer to access data consistency, slightly divided access control, allow constraints to be guaranteed, and provide class authors for full elasticity.
- Protected is not more encapsulated than public.