Cpp Class Access Modifiers
[ C++ Classes & Objects](#)
In C++ Object-Oriented Programming (OOP), data encapsulation is one of the core concepts. Simply put, it means "hiding" the data and only exposing necessary interfaces to the outside world to ensure data security.
To control who can see this data, C++ provides three keywords known as **access modifiers**:
* **`public`**
* **`private`**
* **`protected`**
class Base{public: protected: private: };
To make it easier to understand, we can imagine a **class (Class) as your home**:
| Modifier | Real-World Analogy | Who Can Access? | Typical Use |
| --- | --- | --- | --- |
| **public** | **Living Room / Front Door** | **Everyone** (inside the class, derived classes, external code) | Interface functions (APIs) provided to the outside. |
| **protected** | **Bedroom** | **You and your children** (inside the class, derived classes) | Data for use only within the family (inheritance hierarchy). |
| **private** | **Safe** | **Only you yourself** (only within the class itself) | Core data, variables you don't want modified arbitrarily. |
> **Note**: If no modifier is specified, C++ class members are **`private` by default**.
## Public Members
**Public** members can be accessed from anywhere in the program, without needing to go through member functions for reading or writing. An example is shown below:
## Example
#includeusing namespace std; class Line{public: double length; void setLength(double len); double getLength(void); }; double Line::getLength(void){return length ; }void Line::setLength(double len){length = len; }int main(){Line line; line.setLength(6.0); cout<<"Length of line : "<<line.getLength()<<endl; line.length = 10.0; cout<<"Length of line : "<<line.length<<endl; return 0; }
When the above code is compiled and executed, it produces the following result:
Length of line : 6Length of line : 10
## Private Members
Private members are completely closed off from outside 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 permissions can manipulate these contents.
If no access specifier is used in a class, members are private by default. As shown in the following example, `width` automatically falls into the private section, indicating that unspecified members are treated as private:
## Example
class Box{double width; public: double length; void setWidth(double wid); double getWidth(void); };
In practice, we usually define data in the private section and related functions in the public section, so that these functions can be called from outside the class, as shown below:
## Example
#includeusing namespace std; class Box{public: double length; void setWidth(double wid); double getWidth(void); private: double width; }; double Box::getWidth(void){return width ; }void Box::setWidth(double wid){width = wid; }int main(){Box box; box.length = 10.0; cout<<"Length of box : "<<box.length<<endl; box.setWidth(10.0); cout<<"Width of box : "<<box.getWidth()<<endl; return 0; }
When the above code is compiled and executed, it produces the following result:
Length of box : 10Width of box : 10
## Protected Members
The existence of `protected` is mainly for **inheritance**.
* Without inheritance, it is the same as `private` (invisible to outsiders).
* With inheritance, **derived classes can access the `protected` members of the base class**, but cannot access `private` members.
In the next chapter, you will learn about derived classes and inheritance. Now you can see in the example below that we derived a subclass **SmallBox** from the base class **Box**.
The following example is similar to the previous one, but here the **width** member can be accessed by any member function of the derived class `SmallBox`.
## Example
#includeusing namespace std; class Box{protected: double width; }; class SmallBox:Box{public: void setSmallWidth(double wid); double getSmallWidth(void); }; double SmallBox::getSmallWidth(void){return width ; }void SmallBox::setSmallWidth(double wid){width = wid; }int main(){SmallBox box; box.setSmallWidth(5.0); cout<<"Width of box : "<<box.getSmallWidth()< **The inheritance method determines the maximum permission of base class members in the derived class.**
>
> If the inheritance method is stricter than the member's original permission, the member's permission will be "downgraded" to the level of the inheritance method.
### Permission Change Table
| Original Permission of Base Class Member | **Public Inheritance** (Most Common) | **Protected Inheritance** | **Private Inheritance** |
| --- | --- | --- | --- |
| **public** | Remains public | Downgraded to protected | Downgraded to private |
| **protected** | Remains protected | Remains protected | Downgraded to private |
| **private** | **Inaccessible** | **Inaccessible** | **Inaccessible** |
_Note: "Inaccessible" means the subclass code cannot directly use the variable, but the variable still exists in memory._
### Comprehensive Demonstration Code
For clarity, we rename the variables to `pub_var` (public), `pro_var` (protected), and `pri_var` (private).
## Example
#include
using namespace std;
class Parent {
public:
int pub_var;
protected:
int pro_var;
private:
int pri_var;// Only Parent itself can modify
public:
Parent(){ pub_var =1; pro_var =2; pri_var =3;}
};
// 1. Public Inheritance - Most common, preserves original permissions
class ChildA :public Parent {
public:
void test(){
cout<< pub_var << endl;// OK
cout<< pro_var << endl;// OK
// cout << pri_var << endl; // Error! Base class private member is not visible
}
};
// 2. Protected Inheritance - Everything becomes protected
class ChildB :protected Parent {
public:
void test(){
cout<< pub_var << endl;// OK, but in ChildB's view, 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 in ChildC's view, it is private
cout<< pro_var << endl;// OK, but in ChildC's view, it is private
}
};
int main(){
ChildA a;
cout<< a.pub_var<< endl;// OK, accessible from outside
// cout << a.pro_var << endl; // Error, protected is not accessible from outside
ChildB b;
// cout << b.pub_var << endl; // Error! Because of protected inheritance, pub_var becomes protected outside
ChildC c;
// cout << c.pub_var << endl; // Error! Because of private inheritance, pub_var becomes private outside
return 0;
}
* * *
## Summary
* **Public**: Accessible to everyone. Used for interfaces (APIs).
* **Private**: Only accessible to the class itself. Used for storing data (default secure option).
* **Protected**: Only accessible to the "family" (inheritance chain). Used to provide access for subclasses.
**Inheritance**:
* **Public Inheritance**: The permissions of the base class members remain unchanged (most common).
* **Private/Protected Inheritance**: Tightens the permissions of base class members, typically used for special implementation scenarios.
[ C++ Classes & Objects](#)
YouTip