Intermediate level · Module 2: Inheritance and Virtual Functions · Lesson 1 of 3
Inheritance in C++
Derive classes from a base class, call base constructors and control access with public, protected and private.
In this lesson you will
- Write derived classes with public inheritance
- Call base-class constructors from derived constructors
Key concepts
base and derived classpublic inheritanceprotectedbase constructor call
The lesson
class Nurse : public Staff means a Nurse is a Staff: it inherits Staff's public and protected members. Public inheritance is the normal form; it preserves the base class's public interface.
A derived constructor initialises its base first, in the member initializer list: Nurse(std::string name, int shifts) : Staff{std::move(name)}, shifts_{shifts} {}. Members marked protected are visible to derived classes but not to other code.
Inherit only for genuine is-a relationships where the derived class can be used everywhere the base is expected. For has-a relationships, such as a Clinic having Staff, use members (composition).
Step by step
- Write a Staff base class with a name.
- Derive Doctor and Nurse with their own data.
- Call the base constructor from each derived constructor.
- Try to access a private base member from a derived class and read the error.
Practice activity
Create a small hierarchy of three staff types sharing a base class and print each one's details.
Expected result: Each type initialises its base correctly and prints its own and inherited information.
Check your understanding
-
How does a derived constructor initialise its base?
Show answer
In its member initializer list, by calling the base constructor.
-
Who can access protected members?
Show answer
The class itself and classes derived from it.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.