C++ Inheritance
Learn how to model is-a relationships using inheritance: build class hierarchies, reuse code, and write polymorphic programs in C++.
What Is Inheritance?
Inheritance is a fundamental mechanism in C++ that lets a new class derive from an existing class, automatically gaining its data members and member functions. The existing class is called the base class (or parent), and the new class is called the derived class (or child).
The Is-A Relationship
Inheritance models an is-a relationship: every derived object is also a base object. This is different from has-a (composition), where one object contains another.
Why Inheritance Matters
The Syntax of Inheritance
Access Specifiers in Inheritance
Public vs Protected vs Private
| Base Member | public inheritance | protected inheritance | private inheritance |
|---|---|---|---|
| public | public | protected | private |
| protected | protected | protected | private |
| private | inaccessible | inaccessible | inaccessible |
How to Apply Inheritance
Example 1: Shape Hierarchy
Example 2: Constructor Chaining
Example 3: A Vehicle Hierarchy
Overriding Member Functions
Calling the Base Version
A Glimpse of Polymorphism
Common Mistakes
Inheritance Summary
| Concept | Key Point | Example |
|---|---|---|
| Is-A Relationship | Derived is a Base | Dog is an Animal |
| Syntax | class D : public B | class Dog : public Animal |
| Access | public and protected inherited | private stays inaccessible |
| Constructors | Base runs first, derived second | D(args) : B(args) {} |
| Overriding | Redefine base function in derived | void speak() in Dog |
| Scope Resolution | Call base version explicitly | Animal::speak() |
Question 1 of 5
Which keyword is used to establish a public inheritance relationship between a derived class and a base class?
Question 2 of 5
A Student class inherits from a Person class. Which members of Person can Student directly access?
Question 3 of 5
When a Dog object is created (where Dog inherits from Animal), which constructor runs first?
Question 4 of 5
A Car class has an Engine as a data member. A SportsCar class inherits from Car. Which relationship is modeled incorrectly?
Question 5 of 5
How does a derived class call the base class version of an overridden function named display()?