Inheritance

Some classes are special kinds of other classes. A car is a vehicle, and so is a truck. All vehicles have a brand and can honk, but only a car has a trunk. Inheritance lets you write the shared parts once, in a base class, and then build more specific classes on top of it:

#include <iostream>
#include <string>
using namespace std;

class Vehicle {
public:
    string brand;

    void honk() {
        cout << brand << " says beep" << "\n";
    }
};

class Car : public Vehicle {
public:
    void openTrunk() {
        cout << brand << " trunk is open" << "\n";
    }
};

int main() {
    Car c;
    c.brand = "Volvo";
    c.honk();
    c.openTrunk();
    return 0;
}

Output:

Volvo says beep
Volvo trunk is open

class Car : public Vehicle makes Car a derived class of Vehicle. A Car gets all the public members of Vehicle. That is why c.brand and c.honk() work, even though the Car class never declares them. Car also adds its own method, openTrunk, and that method can use the inherited brand.

Always write public before the base class name. If you leave it out, the inherited members become hidden from code outside the class, and c.honk() in main no longer compiles.

Passing values to the base constructor

When the base class has a constructor with parameters, the derived class must pass values to it. You do this after a colon, before the constructor's body:

#include <iostream>
#include <string>
using namespace std;

class Vehicle {
public:
    string brand;

    Vehicle(string b) {
        brand = b;
    }

    void honk() {
        cout << brand << " says beep" << "\n";
    }
};

class Car : public Vehicle {
public:
    Car(string b) : Vehicle(b) {
    }
};

int main() {
    Car c("Toyota");
    c.honk();
    return 0;
}

Output:

Toyota says beep

Car(string b) : Vehicle(b) means: when a Car is created, first call the Vehicle constructor with b. The Vehicle constructor sets brand, so the Car constructor's own body can stay empty.

"Is a" or "has a"?

Before you use inheritance, say the sentence "a Car is a Vehicle". If it is true, inheritance fits. Now try "a Car is an Engine". That is false: a car has an engine. In that case, put an Engine member inside Car instead of inheriting from Engine.

A derived class can also write its own version of an inherited method. That is the topic of the next lesson.

In the exercise, complete the class header so that Dog inherits from Animal.