Clause 22: Declare a member variable private
C + + We need to declare member variables private, we instruct access to public, private and protected, why we choose to use the member variable declaration as private it.
If you use public, any external function or external class can access it, making the whole class system super fragile, the external change is very easy to the system fatal attack, so many member variables should be hidden, through the public function interface access.
By encapsulating member variables on classes, accessing member variables through functions, hiding member variables behind function interfaces, you can provide flexibility for "all possible implementations", such as allowing member variables to be blocked or ready for easy notification to other objects, You can verify class constraints and the prerequisites and time state of a function, while ensuring that class constraints are always maintained because only member functions can affect them, and you also retain the right to change the code later.
The protected member variable is mainly used in the inheritance system of the class, so what is the encapsulation of it? Actually more than the packaging of the public member variable, and public member variables change, many parts of the class will be destroyed, then protected. Will destroy more, including the code in this class and subclasses.
Summarize:
1, please declare the member variable private, this can give users access to data consistency, access control can be subdivided, the promise of constraints to obtain the guarantee, and provide class authors to fully achieve flexibility;
2, protected is not more than public packaging.