C + + is the member variable declared as private---"effective C + +" __c++

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.