C++ Inheritance Access
🔐 C++ Inheritance Access (Access Modes)
Inheritance access in C++ defines how the members of a base class are inherited into a derived class.
It depends on two things:
-
Access specifiers of base class members (
public,protected,private) -
Inheritance mode (
public,protected,private)
🔹 1. Base Class Member Access
| Member | Accessible in Derived Class |
|---|---|
public |
✔ |
protected |
✔ |
private |
❌ |
👉 private members are never inherited directly
🔹 2. Inheritance Modes
🔹 3. Public Inheritance (Most Common)
| Base Member | Becomes in Derived |
|---|---|
| public | public |
| protected | protected |
| private | not accessible |
✔ Represents is-a relationship
🔹 4. Protected Inheritance
| Base Member | Becomes in Derived |
|---|---|
| public | protected |
| protected | protected |
| private | not accessible |
✔ Limits outside access
❌ Not commonly used
🔹 5. Private Inheritance
| Base Member | Becomes in Derived |
|---|---|
| public | private |
| protected | private |
| private | not accessible |
✔ Used for has-a implementation
❌ No polymorphism
🔹 6. Accessing Inherited Members
🔹 7. Access from Object (Important)
Protected members are accessible inside class, not via object.
🔹 8. Real-World Example
✔ Car is a Vehicle
✔ Speed not accessible directly by user
🔹 9. Quick Summary Table
| Inheritance | public | protected | private |
|---|---|---|---|
| public | public | protected | ❌ |
| protected | protected | protected | ❌ |
| private | private | private | ❌ |
❌ Common Mistakes
➡ Breaks is-a relationship unintentionally.
📌 Summary
-
Inheritance access controls visibility of base members
-
Public inheritance preserves access levels
-
Protected/private inheritance restrict access
-
privatemembers are never inherited -
Use public inheritance for polymorphism
