Lesson 14 of 19

Inheritance

Inheritance

Inheritance lets a class (derived class) reuse and extend the behavior of another class (base class). It models an "is-a" relationship.

Syntax

class Animal {
public:
    string name;

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

    void breathe() {
        cout << name << " breathes" << endl;
    }
};

class Dog : public Animal {
public:
    Dog(string n) : Animal(n) {}  // call base constructor

    void bark() {
        cout << name << " barks: Woof!" << endl;
    }
};

Dog inherits name and breathe() from Animal, and adds bark().

Dog d("Rex");
d.breathe();  // Rex breathes
d.bark();     // Rex barks: Woof!

Calling the Base Constructor

The derived class constructor must call the base constructor in the initializer list:

class Cat : public Animal {
public:
    Cat(string n) : Animal(n) {}  // passes n to Animal's constructor
};

Overriding Methods

A derived class can provide its own version of an inherited method:

class Animal {
public:
    void speak() {
        cout << "..." << endl;
    }
};

class Dog : public Animal {
public:
    void speak() {  // hides Animal::speak
        cout << "Woof!" << endl;
    }
};

Multiple Levels

Inheritance can be chained:

class LivingThing { ... };
class Animal : public LivingThing { ... };
class Dog : public Animal { ... };

Dog inherits from both Animal and LivingThing.

Access Control in Inheritance

With public inheritance:

  • public members of the base remain public
  • private members of the base are inaccessible in derived
  • Use protected for members that derived classes can access but outsiders cannot

Your Task

Create:

  • An Animal base class with a name and a breathe() method
  • A Dog class that inherits Animal and adds bark()
  • A Cat class that inherits Animal and adds meow()

Create one dog and one cat, call their methods.

JSCPP loading...
Loading...
Click "Run" to execute your code.