C/C++ Arena

Step 1 of 9

Inheritance

Often several classes share most of their data and behavior: every vehicle has a name and a speed, every account has an owner and a balance. Inheritance lets a new class (the derived class) start from an existing one (the base class), getting all its members, and then add more.

The relationship must be is-a: a Car is a Vehicle, so anything you can do with a vehicle you can do with a car.

#include <iostream>
#include <string>

class Vehicle {
public:
    Vehicle(std::string name, int wheels) : name_(name), wheels_(wheels) {}
    std::string summary() const { return name_ + " on " + std::to_string(wheels_) + " wheels"; }

private:
    std::string name_;
    int wheels_;
};

class Truck : public Vehicle {
public:
    Truck(std::string name, int load) : Vehicle(name, 6), load_(load) {}
    int load() const { return load_; }

private:
    int load_;
};

int main() {
    Truck t("hauler", 12);
    std::cout << t.summary() << ", carrying " << t.load() << " tons\n";
    Vehicle v("bike", 2);
    std::cout << v.summary() << "\n";
}
hauler on 6 wheels, carrying 12 tons
bike on 2 wheels

How it works

Common mistakes

Your turn: make Sniper inherit from Weapon and set the base part through the base constructor.

Next: virtual and override