11.3 — Inheritance: building on a class
Read one box at a time. No rush.
"is a" relationships#
A dog is an animal. A cat is an animal. Inheritance lets a class take everything from another class, then add more.
C++▶ Run
class Animal{public: Animal(std::string name) : m_name { name } { } std::string name() const { return m_name; } private: std::string m_name {};}; class Dog : public Animal{public: Dog(std::string name) : Animal { name } { } void fetch() const { std::cout << name() << " fetches the ball!\n"; }}; int main(){ Dog rex { "Rex" }; std::cout << rex.name() << '\n'; // from Animal rex.fetch(); // from Dog return 0;}Animalis the base class (the parent).Dogis the derived class (the child).: public Animalmeans "Dog is an Animal".
Virtual functions#
To let each child do something its own way, mark the parent's function virtual and the child's override:
C++
class Animal{public: virtual ~Animal() = default; virtual void speak() const { std::cout << "...\n"; }}; class Cat : public Animal{public: void speak() const override { std::cout << "Meow\n"; }}; class Cow : public Animal{public: void speak() const override { std::cout << "Moo\n"; }}; void makeNoise(const Animal& a){ a.speak(); // calls the right version!}makeNoise(Cat{}) prints Meow. makeNoise(Cow{}) prints Moo. This is called polymorphism: one function call, many behaviours.
Watch out
If a class has virtual functions, give it a virtual destructor (like virtual ~Animal() = default;). Otherwise cleanup can go wrong.
Tip: press ← / → to move between lessons, / to search.