C/C++ Arena

Step 2 of 8

virtual and override

Through a base-class reference or pointer, which function runs? By default, the base version. Mark the base function virtual and the actual object's version runs instead. That's polymorphism.

class Enemy {
public:
    virtual std::string sound() const { return "..."; }
    virtual ~Enemy() = default;
};
class Zombie : public Enemy {
public:
    std::string sound() const override { return "brains"; }
};

const Enemy& e = Zombie{};
e.sound();   // "brains"

Write override on the derived version: the compiler then checks that you really are overriding something (typos become errors).

Your turn: make Knife and Grenade override attack, returning "slash" and "boom".

Previous: Inheritance Next: Abstract classes