Appearance
Public / Private / Protected
Access specifiers control who can access the members of a class.
- public → accessible everywhere
- private → accessible only within the class
- protected → accessible within class + derived classes
Basic Example
cpp
class Person {
public:
string name; // accessible everywhere
protected:
int age; // accessible in class + derived classes
private:
string password; // accessible only inside this class
};
int main() {
Person p;
p.name = "Alice"; // OK — public
p.age = 25; // ERROR — protected
p.password = "1234"; // ERROR — private
}Access Table
| Same Class | Derived Class | Outside Class | |
|---|---|---|---|
| public | Yes | Yes | Yes |
| protected | Yes | Yes | No |
| private | Yes | No | No |
Inheritance + Access Specifiers
cpp
class Base { public: int x; protected: int y; private: int z; };
// Public Inheritance (most common):
class Derived : public Base {
// x → public (stays public)
// y → protected (stays protected)
// z → not accessible
};
// Protected Inheritance:
class Derived : protected Base {
// x → protected (demoted)
// y → protected
};
// Private Inheritance:
class Derived : private Base {
// x → private (demoted)
// y → private (demoted)
};Full Inheritance Access Table
| Base Member | Public Inheritance | Protected Inheritance | Private Inheritance |
|---|---|---|---|
| public | public | protected | private |
| protected | protected | protected | private |
| private | Not accessible | Not accessible | Not accessible |
Friend — Special Access
cpp
class Box {
private:
int length = 10;
friend class BoxHelper; // BoxHelper can access private members
friend void printBox(Box); // function can access private members
};
friendbreaks encapsulation — use sparingly.
Struct vs Class
cpp
struct MyStruct { int x; }; // public by default
class MyClass { int x; }; // private by default
// Only difference between struct and class in C++ is default access.Key Points
| Point | Detail |
|---|---|
Default in class | private |
Default in struct | public |
| Protected use | Inheritance scenarios |
| Private use | Encapsulation |
| Friend | Bypasses access rules |
| Most used inheritance | public |
One-liner: "Public members are accessible everywhere, private only within the class, and protected within the class and its derived classes — controlling encapsulation and inheritance behavior."