C++ Class access modifiers
In C++ object-oriented programming (OOP), data encapsulation is one of the core concepts. Simply put, it means "hiding" the data and only exposing the necessary interfaces to the outside world to ensure data safety.
To control who can see this data, C++ provides three keywords, calledAccess modifiers:
public(public)private(private)protected(protected)
For ease of understanding, we can think of aclass as your home:
| Modifiers | Real-world analogy | Who can access? | Typical use |
|---|---|---|---|
| public | Living room/Front door | Everyone(inside the class, subclasses, external code) | Interface functions (API) provided to the outside world. |
| protected | Bedroom | You and your children(inside the class, subclasses) | Data used only within the family (inheritance hierarchy). |
| private | Safe | Only yourself(only within the class itself) | Core data, variables that should not be modified casually. |
Note: If no modifier is written, C++ class membersThe default is
private(private).
public members
publicMembers can be accessed anywhere in the program without reading or writing through member functions, as shown in the following example:
Example
When the above code is compiled and executed, it produces the following results:
Length of line : 6 Length of line : 10
private members
Private members are completely enclosed to the outside of the class; external code cannot read, modify, or call them, and derived classes also have no direct access rights. Only the class's own member functions and entities granted friend permission can operate on these contents.
If no access specifier is used in the class, members default to private. As shown in the example below, width automatically falls into the private area, indicating that members not explicitly marked are all treated as private:
Example
In practice, we generally define data in the private section and define related functions in the public section, so that these functions can also be called outside the class, as shown below:
Example
When the above code is compiled and executed, it produces the following results:
Length of box : 10 Width of box : 10
protected members
protectedThe existence of ... is mainly toInheritance。
- If there is no inheritance, it and
privatethe same (not visible to outsiders). - If there is inheritance,A subclass (derived class) can access the parent class's
protectedmember, but cannot accessprivatemembers.
In the next chapter, you will learn about derived classes and inheritance. Now you can see in the example below, we from the parent classBoxderived a subclasssmallBox。
The example below is similar to the previous example; herewidthMembers can be accessed by any member function of the derived class smallBox.
Example
When the above code is compiled and executed, it produces the following results:
Width of box : 5
Access permission changes in inheritance
When you define a subclass (such asclass B : public A), after the colonpublicis also an access modifier; it determinesHow the parent class's members "appear" in the child class。
This looks complicated, but you only need to remember thisDowngrade principle:
The inheritance method determines the highest permission that parent class members have in the child class.
If the inheritance method is stricter than the member's original permission, the member's permission is "downgraded" to the level of the inheritance method.
Access change table
| the original access rights of base class members | public inheritance(most commonly used) | protected inheritance | private inheritance |
|---|---|---|---|
| public | remain public | downgraded to protected | downgraded to private |
| protected | remain protected | remain protected | downgraded to private |
| private | Inaccessible | Inaccessible | Inaccessible |
Note: inaccessible means the child class code cannot directly use the variable, but the variable still exists in memory.
comprehensive demonstration code
For clarity, we rename the variable topub_var(public),pro_var(protected),pri_var(private).
Example
using namespace std;
class Parent {
public:
int pub_var;
protected:
int pro_var;
private:
int pri_var; // Only Parent itself can access
public:
Parent() { pub_var = 1; pro_var = 2; pri_var = 3; }
};
// 1. Public Inheritance - most common, true to the original
class ChildA : public Parent {
public:
void test() {
cout << pub_var << endl; // OK
cout << pro_var << endl; // OK
// cout << pri_var << endl; // Error! Parent class private members are not visible
}
};
// 2. Protected Inheritance - everything becomes protected
class ChildB : protected Parent {
public:
void test() {
cout << pub_var << endl; // OK, but from ChildB's perspective, it is protected
cout << pro_var << endl; // OK
}
};
// 3. Private Inheritance - everything becomes private
class ChildC : private Parent {
public:
void test() {
cout << pub_var << endl; // OK, but from ChildC's perspective, it is private
cout << pro_var << endl; // OK, but from ChildC's perspective, it is private
}
};
int main() {
ChildA a;
cout << a.pub_var << endl; // OK, accessible externally
// cout << a.pro_var << endl; // Error, protected is not accessible externally
ChildB b;
// cout << b.pub_var << endl; // Error! Because it is protected inheritance, pub_var becomes protected externally
ChildC c;
// cout << c.pub_var << endl; // Error! Because it is private inheritance, pub_var becomes private externally
return 0;
}
Summary
- Public: Anyone can use it. Used as interfaces (API).
- Private: Only itself can use it. Used for storing data (default safe option).
- Protected: Only the family (inheritance chain) can use it. Used to leave a backdoor for child classes.
Inheritance:
- Public inheritance: The parent class's attributes remain unchanged (most commonly used).
- Private/Protected inheritance: Will tighten the permissions of parent class members, usually used in special implementation scenarios.