CPP Inheritance

🧬 CPP Inheritance
CPP Inheritance is a key idea in Object-Oriented Programming is a way to design and build software. It uses objects to represent real-world things. Each object can have its own data and functions. This makes it easier to manage and organize code. Developers can create reusable code, which saves time. Overall, Object-Oriented Programming helps in creating clear and efficient software (OOP). It lets a class (child) reuse and build on the properties and behaviors of another class (parent).
🔹 1. Why Use Inheritance?
Code reusability
Reduces duplication
Creates logical hierarchy
Improves maintainability
🔹 2. Basic Syntax
🔹 3. Simple Inheritance Example
🔹 4. Types of Inheritance in C++
1️⃣ Single Inheritance
2️⃣ Multilevel Inheritance
3️⃣ Multiple Inheritance
⚠️ Can cause ambiguity
4️⃣ Hierarchical Inheritance
5️⃣ Hybrid Inheritance
Combination of two or more types.
🔹 5. Access Specifiers in Inheritance
| Member | Accessible in Derived |
|---|---|
public | ✔ |
protected | ✔ |
private | ❌ |
🔹 6. Inheritance Access Modes
| Mode | Base Public | Base Protected |
|---|---|---|
| public | public | protected |
| protected | protected | protected |
| private | private | private |
🔹 7. Constructor in Inheritance
✔ Base constructor is called first
🔹 8. Method Overriding
🔹 9. virtual Keyword (Runtime Polymorphism)
🔹 10. Diamond Problem & Virtual Inheritance
✔ Solves ambiguity
❌ Common Mistakes
➡ Limits access unintentionally.
🔁 Inheritance vs Composition
| Inheritance | Composition |
|---|---|
| “is-a” relationship | “has-a” relationship |
| Tight coupling | Loose coupling |
| Less flexible | More flexible |
📌 Summary
Inheritance enables code reuse
Child class inherits from parent
Supports multiple inheritance types
virtualenables runtime polymorphismUse virtual inheritance to solve diamond problem
