CPP Inheritance

C++ Tutorial

🧬 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

class B : public A {};

2️⃣ Multilevel Inheritance

class A {};
class B : public A {};
class C : public B {};

3️⃣ Multiple Inheritance

class A {};
class B {};
class C : public A, public B {};

⚠️ Can cause ambiguity


4️⃣ Hierarchical Inheritance

class A {};
class B : public A {};
class C : public A {};

5️⃣ Hybrid Inheritance

Combination of two or more types.


🔹 5. Access Specifiers in Inheritance


MemberAccessible in Derived
public
protected
private

🔹 6. Inheritance Access Modes

ModeBase PublicBase Protected
publicpublicprotected
protectedprotectedprotected
privateprivateprivate

🔹 7. Constructor in Inheritance


 

✔ Base constructor is called first


🔹 8. Method Overriding


 


🔹 9. virtual Keyword (Runtime Polymorphism)

Animal* a;
Dog d;
a = &d;
a->sound(); // Dog barks

🔹 10. Diamond Problem & Virtual Inheritance

class A {};
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {};

✔ Solves ambiguity


❌ Common Mistakes

class Child : private Parent {};

➡ Limits access unintentionally.


🔁 Inheritance vs Composition

InheritanceComposition
“is-a” relationship“has-a” relationship
Tight couplingLoose coupling
Less flexibleMore flexible

📌 Summary

  • Inheritance enables code reuse

  • Child class inherits from parent

  • Supports multiple inheritance types

  • virtual enables runtime polymorphism

  • Use virtual inheritance to solve diamond problem

You may also like...