Inheritance – Complete Tutorial
1. What is Inheritance?
Inheritance is a mechanism in C++ where a class (derived class) can acquire properties and behaviors from another class (base class).
It promotes code reuse, modularity, and hierarchical relationships.
2. Single Inheritance
A derived class inherits from a single base class.
Example:
3. Multilevel Inheritance
A chain of inheritance where a class is derived from another derived class.
Example:
4. Hierarchical Inheritance
Multiple classes inherit from a single base class.
Example:
5. Multiple Inheritance
A derived class inherits from more than one base class.
Example:
Usage:
6. Hybrid Inheritance
Combination of two or more types of inheritance (single, multiple, multilevel, hierarchical).
Example:
- Base class → two derived classes → single derived class from them (mix of multiple + multilevel)
7. Virtual Base Class
Virtual base classes solve ambiguity in multiple inheritance (diamond problem).
Example:
Key Points:
- Use
virtualto ensure only one copy of base class exists - Prevents multiple copies in diamond hierarchy
8. Diamond Problem
Occurs in multiple inheritance when two classes inherit from the same base and a derived class inherits from both.
Without virtual inheritance:
Dwill have two copies of A, causing ambiguity.
Solution: Use virtual inheritance as shown above.
Best Practices
- Use inheritance for “is-a” relationships
- Avoid deep inheritance hierarchies
- Prefer composition over inheritance when possible
- Use virtual functions carefully to handle polymorphism
- Always mark base class destructor as virtual if it will be inherited
Common Mistakes
- Forgetting
publickeyword in inheritance - Mixing types of inheritance without planning
- Not using virtual inheritance for diamond problem
- Overusing multiple inheritance, making code hard to maintain
Summary
In this chapter, you learned all types of inheritance in C++, including:
- Single, multilevel, hierarchical, multiple, and hybrid inheritance
- Virtual base classes
- Diamond problem and its solution
Inheritance is a core OOP concept that promotes code reuse and establishes relationships between classes, forming the foundation for polymorphism and abstraction.