Inheritance
Explore the concept of inheritance in C++ to understand how base and derived classes form logical hierarchies representing real-world relationships. Learn construction and destruction order, access specifiers like protected, and differentiate inheritance from composition and aggregation. This lesson helps you structure classes effectively to avoid code duplication and design maintainable object-oriented systems.
We have spent our time defining individual classes. But in the real world, objects are rarely isolated; they belong to hierarchies. A sports car is a car, and a car is a vehicle. If we were to write separate classes for SportsCar, Car, and Vehicle, we would end up copying the same logic for "speed" and "movement" three times. This violates the "Don't Repeat Yourself" (DRY) principle.
In this lesson, we'll use inheritance to write that logic once in a "base" class and share it automatically with "derived" classes. This creates a logical hierarchy that mirrors the real world.
The “is-a” relationship
Inheritance models an "is-a" relationship. When we say Car inherits from Vehicle, we are stating that a Car is a Vehicle.
Base class (parent): The class containing general shared logic (e.g.,
Vehicle).Derived class (child): The class that inherits from the base and adds specific features (e.g.,
Car...
Let's look at why we separate these members.