C++ Inheritance

Inheritance lets one class take on the members of another class, so you can reuse code instead of rewriting it. The class you inherit from is called the base class, and the class that inherits is called the derived class. It is one of the most powerful ways C++ helps you build on top of existing work.

The base class and the derived class

To make one class inherit from another, you write a colon after the derived class name, followed by an access mode (usually public) and the name of the base class. The derived class then automatically has all the public and protected members of the base class.

A simple inheritance example

#include <iostream>
using namespace std;

// Base class
class Vehicle {
  public:
    string brand = "Ford";
    void honk() {
      cout << "Beep beep!\n";
    }
};

// Derived class
class Car : public Vehicle {
  public:
    string model = "Mustang";
};

int main() {
  Car myCar;
  myCar.honk();                       // inherited from Vehicle
  cout << myCar.brand << " " << myCar.model;
  return 0;
}

Notice how myCar can call honk() and use brand even though those were defined in Vehicle. The Car class received them through inheritance, which saved us from writing them again.

  • Reuse: shared behavior lives in the base class, used by every derived class.
  • Organization: related classes form a clear family tree.
  • Extension: a derived class can add its own new members on top.

The protected specifier and inheritance

#include <iostream>
using namespace std;

class Animal {
  protected:
    int legs = 4;   // hidden from outside, but visible to children

  public:
    void describe() {
      cout << "This animal has " << legs << " legs\n";
    }
};

class Dog : public Animal {
  public:
    void fetch() {
      cout << "Running on " << legs << " legs to fetch!\n"; // legs is reachable
    }
};

int main() {
  Dog d;
  d.describe();
  d.fetch();
  return 0;
}
Note: This is where protected earns its place: legs is not accessible from main(), but Dog can still use it because it inherits from Animal. Use protected for data that base and derived classes share but outsiders should not touch.
TermMeaning
Base classThe class whose members are inherited
Derived classThe class that inherits and can add more
public inheritancePublic stays public, protected stays protected in the child

A good way to test whether inheritance fits is the 'is a' check: a Car is a Vehicle, a Dog is an Animal. When that sentence sounds natural, inheritance is usually the right tool.

Exercise: C++ Inheritance

In 'class Derived : public Base', what does the public keyword before Base specify?