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
class Truck : public Vehiclemeans "Truck inherits from Vehicle". Always writepublichere; without it, the inherited members become private to the outside world, which is almost never what you want.- A
Truckobject contains a completeVehicleinside it, plus its ownload_. t.summary()works becausesummarywas inherited.- The base part must be constructed first, and the derived class does that in its initializer list:
: Vehicle(name, 6). That's the only way to call the base constructor, and it's required when the base has no default constructor. name_andwheels_areprivatetoVehicle, so evenTruck's own code can't touch them directly. It usesVehicle's public functions like everyone else.
Common mistakes
- Trying to set base members in the derived constructor's body (
name_ = name;). They're private to the base; pass them to the base constructor instead. - Using inheritance just to reuse code when there's no is-a relationship. That's what members are for (more in step 7).
Your turn: make Sniper inherit from Weapon and set the base part through the base constructor.