Inheritance

11.1 - Inheritance intro


Inheritance allows a class (the derived class) to inherit from another class (the parent class).

For example, the class Dog extends the Animal class. By doing so, the Dog class inherits the name field and eat and make_sound methods, allowing a Dog object to use them.

The Dog class can still creates its own property, such as the chase_cat method which is exclusive to Dog and not for other Animal.

This code define the class Dog by inheriting Animal with the public access specifier:

class Dog : public Animal
{
    // ...
}

Task

Make Iggy the dog eat, make sound, and then chase a cat.

  • In the main function, call the following functions eat, make_sound, and then chase_cat on iggy:
    • iggy.eat()
    • iggy.make_sound()
    • iggy.chase_cat()
#include <iostream> class Animal { public: void eat() { std::cout << name << " eats food." << std::endl; } void make_sound() { std::cout << name << " makes a sound." << std::endl; } std::string name; }; class Dog : public Animal { public: void chase_cat() { std::cout << name << " chases a cat." << std::endl; } }; int main() { Dog iggy{"Iggy"}; }