As a programmer, you can increase the integrity of software built with C++ by controlling access to class member data and functions. Class members can be declared as having private, protected, or public access, as shown in Table 10.1.
Table 10.1 Member-Access Control
Type of Access | Meaning |
private | Class members declared as private can be used only by member functions and friends (classes or functions) of the class. |
protected | Class members declared as protected can be used by member functions and friends (classes or functions) of the class. Additionally, they can be used by classes derived from the class. |
public | Class members declared as public can be used by any function. |
Access control prevents you from using objects in ways they were not intended to be used. This protection is lost when explicit type conversions (casts) are performed.
Note:
Access control is equally applicable to all names: member functions, member data, nested classes, and enumerators.
The default access to class members (members of a class type declared using the class keyword) is private; to change the access in a class declaration, you must use the public or protected keyword. The default access to struct and union members is public; to change the access in a struct or union declaration, you must use the private or protected keyword.