Skip to content

Module 6 · Inheritance and Polymorphism — topic 1 of 5

Inheritance

A derived class inherits members of a base class and can extend them. Learn public inheritance, constructor chaining, protected members, and types of inheritance.

Beginner 15 min read·Lesson 22 of 40 in C++ Programming

Learning objectives

  • Derive classes with public inheritance
  • Call base-class constructors from derived constructors
  • Distinguish single, multilevel, hierarchical and multiple inheritance

Definition

Inheritance is a mechanism by which a derived class acquires the members of one or more base classes, modelling an “is-a” relationship; with public inheritance, a derived object can be used wherever a base object is expected.

Introduction

A SavingsAccount is an Account with interest; a Manager is an Employee with a team. Inheritance lets the derived class reuse everything in the base and add or adjust behaviour.

Why it matters

Inheritance is one of the four OOP pillars and the foundation for polymorphism.

Misused inheritance causes rigid designs; understanding when to use it (is-a) versus composition (has-a) is a key design skill.

Detailed explanation

class Derived : public Base { ... }; — public members of Base stay public in Derived. Protected members are accessible in Derived but not outside. Private members exist in the derived object but are not directly accessible.

Construction order: base first, then members, then the derived constructor body. Destruction is the reverse. Pass arguments to the base in the initialiser list: Derived(int x) : Base(x) {}.

Types: single (B : A), multilevel (C : B : A), hierarchical (B : A and C : A), multiple (C : A, B). Diamond shapes in multiple inheritance are resolved with virtual inheritance.

Prefer composition (a member object) when the relationship is has-a: a Car has an Engine, it is not an engine.

Syntax

C++
class Employee {
public:
Employee(std::string name, double salary);
protected:
std::string name_;
double salary_;
};
class Manager : public Employee {
public:
Manager(std::string name, double salary, int team)
: Employee(std::move(name), salary), team_(team) {}
private:
int team_;
};
  • Use public inheritance for is-a relationships.
  • Base constructors are called in the initialiser list.
  • Default inheritance for class is private, for struct public.

Code examples

Reusing and extending

C++
#include <iostream>
#include <string>
class Animal {
public:
explicit Animal(std::string name) : name_(std::move(name)) {}
void eat() const { std::cout << name_ << " is eating\n"; }
protected:
std::string name_;
};
class Dog : public Animal {
public:
using Animal::Animal; // inherit the constructor
void fetch() const { std::cout << name_ << " fetches the ball\n"; }
};
int main() {
Dog d("Bruno");
d.eat();
d.fetch();
return 0;
}
Output
Bruno is eating
Bruno fetches the ball

Construction and destruction order

C++
#include <iostream>
struct Base { Base() { std::cout << "Base "; } ~Base() { std::cout << "~Base "; } };
struct Derived : Base { Derived() { std::cout << "Derived "; } ~Derived() { std::cout << "~Derived "; } };
int main() {
{ Derived d; }
std::cout << '\n';
return 0;
}
Output
Base Derived ~Derived ~Base

More examples

Multilevel inheritance with constructor chaining

C++
#include <iostream>
#include <string>
class Account {
public:
Account(std::string owner, double balance) : owner_(std::move(owner)), balance_(balance) {}
double balance() const { return balance_; }
protected:
std::string owner_;
double balance_;
};
class SavingsAccount : public Account {
public:
SavingsAccount(std::string owner, double balance, double rate) : Account(std::move(owner), balance), rate_(rate) {}
void add_interest() { balance_ += balance_ * rate_ / 100; }
protected:
double rate_;
};
class StudentSavings : public SavingsAccount {
public:
StudentSavings(std::string owner, double balance) : SavingsAccount(std::move(owner), balance, 4.0) {}
void describe() const { std::cout << owner_ << " (student) at " << rate_ << "%: " << balance_ << '\n'; }
};
int main() {
StudentSavings s("Ravi", 5000);
s.add_interest();
s.describe();
std::cout << s.balance() << '\n';
return 0;
}
Output
Ravi (student) at 4%: 5200
5200

Step-by-step explanation

  • Each constructor passes arguments up to its direct base.
  • StudentSavings fixes the rate at 4%.
  • add_interest (from SavingsAccount) updates balance_ (from Account).
  • describe can read protected members of both ancestors.

Expected output

Running “Multilevel inheritance with constructor chaining” prints exactly:

TextOutput
Ravi (student) at 4%: 5200
5200

Practical applications

  • GUI frameworks: Button is-a Widget.
  • Game entities: Enemy is-a Character.
  • Exception hierarchies: std::out_of_range is-a std::logic_error is-a std::exception.

Best practices

  • Use public inheritance only for genuine is-a relationships.
  • Keep data private and expose protected functions rather than protected data where possible.
  • Prefer composition by default.

Common mistakes

Forgetting to call a base constructor that needs arguments

Avoid

class Dog : public Animal { public: Dog() {} };

Prefer

class Dog : public Animal { public: Dog() : Animal("dog") {} };

If Animal has no default constructor, Dog must pass arguments to it.

Inheriting for code reuse when it's not is-a

Avoid

class Car : public Engine {};

Prefer

class Car { Engine engine_; };

A car has an engine; use composition.

Important notes

  • Converting a derived object to a base object by value 'slices' off the derived part; pass by reference or pointer to keep the full object.
  • Virtual inheritance (class B : virtual public A) shares one A sub-object in diamond hierarchies.

Key takeaways

  • Derived classes inherit and extend bases.
  • Bases construct first and destroy last.
  • Use inheritance for is-a, composition for has-a.

Try it yourself

  1. 1
    Create Vehicle → Car → ElectricCar with constructors that chain correctly and a description method.
  2. 2
    Rewrite a Car : public Engine design using composition.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

6 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhich relationship should public inheritance model?
  • BeginnerA `protected` member of a base class is accessible in…
Practise this topic