← C++ from Scratch Lesson 42 of 62 · 10 XP

Inheritance

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A derived class gets the fields and methods of the base class and adds its own:

class Unit {
public:
    Unit(std::string n, int hp) : name(n), hp(hp) {}
    std::string info() const { return name + " hp=" + std::to_string(hp); }
protected:                   // visible to descendants, but not from the outside
    std::string name;
    int hp;
};

class Archer : public Unit {          // an Archer is a Unit
public:
    Archer(std::string n) : Unit(n, 80), arrows(10) {}   // the base part is built first
    void shoot() { if (arrows > 0) arrows--; }
    int left() const { return arrows; }
private:
    int arrows;
};

Inheritance expresses "is a" (an archer is a unit). If the relationship is "has a" (a hero has an inventory), you need a field, not a derived class.

Task. Following the example, make Unit and Archer. Read a name and the number of shots k. Create an archer, shoot k times and print info() and how many arrows are left, separated by a space.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.