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
publicbefore the base class name (class Dog : Animal) — for aclass, that defaults toprivateinheritance, which is rarely what's intended.