Lesson 145 +10 XP

Introduction to Inheritance

Introduction to Inheritance

Inheritance lets you build a new class from an existing class. The new class gets all the members of the old one, and you can add your own features on top. It is one of the biggest sources of code reuse in C++.

Base and derived classes

There are two roles:

  • The base class (the parent) is the existing class you build from.
  • The derived class (the child) is the new class that inherits from it.

Inheritance lets us create a new class that reuses, extends, and modifies the behavior of an existing class.

The example: Vehicle and Car

Here is a base class:

class Vehicle {
public:
  string brand;
  void honk() { cout << "Beep!"; }
};

Now a derived class that gets everything from Vehicle, plus its own member:

class Car : public Vehicle {
public:
  int seats = 4;
};

The syntax is class Car : public Vehicle. The derived class name comes first, then a colon, then the base class name prefixed by the access keyword public.

The derived class has all the members

Because Car inherits from Vehicle, a Car object owns the base members AND its own:

Car myCar;
myCar.brand = "Volvo";
myCar.honk();            // came from Vehicle
cout << myCar.seats;     // Car's own member

Reuse is the point

You write honk() and brand once in the base class. Every derived class gets them for free and only adds what is special to itself.

TL;DR

  • Inheritance builds a new class on top of an existing class.
  • The base class is inherited from; the derived class inherits.
  • Syntax: class Car : public Vehicle.
  • The derived class receives every base member and can add its own.
  • Shared code written once in the base is used by every derived class.