Skip to content
AgileLogics
5 min read

Inheritance

Prerequisites: Operator overloading

class Animal {
protected:
    std::string name;

public:
    Animal(std::string n) : name(n) {}

    void makeSound() {
        std::cout << name << " makes a sound" << std::endl;
    }
};

class Dog : public Animal {
public:
    Dog(std::string n) : Animal(n) {}
};

Dog rex("Rex");
rex.makeSound(); // Rex makes a sound — inherited unchanged

: public Animal both inherits Animal's members and controls their visibility through the subclass (public inheritance, used almost always, keeps them at their original visibility).

Common mistakes

  • Forgetting public before the base class name (class Dog : Animal) — for a class, that defaults to private inheritance, which is rarely what's intended.