Skip to content

Inheritance and Polymorphism

Programming C++ Difficulty 1/5

Beginning of the lesson

Inheritance and Polymorphism

Build class families, reuse code, and let one call do many things

Big Idea: Inheritance lets a new class reuse the code of an existing class, adding only what is different. Polymorphism lets you treat many related objects through one shared type, and each object still behaves in its own way. Together they help you write less code that does more.
By the end you will be able to:
  • build a base class and a derived class with : public Base,
  • reuse and extend inherited members, and use protected,
  • call base constructors from a derived constructor,
  • use virtual functions and override for polymorphism,
  • explain why a base class needs a virtual destructor.

1. What is inheritance?

Inheritance lets one class (the derived class) automatically get the members of another class (the base class). The derived class can then add extra things of its own. We write it with a colon and public:

#include <iostream>
using namespace std;

class Animal {              // base class
public:
    void eat() {
        cout << "This animal eats food." << endl;
    }
};

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

int main() {
    Dog d;
    d.eat();    // inherited from Animal
    d.bark();   // Dog's own method
    return 0;
}

Output:

This animal eats food.
Woof!

Dog never wrote an eat() function, yet d.eat() works because Dog inherited it from Animal. We say "a Dog is-an Animal". This is the "is-a" relationship.

2. Picture a class family

One base class can have many derived classes. The arrow means "inherits from" and always points from a child up to its parent:

Animal base class Dog derived Cat derived
Animal is the base class; Dog and Cat are derived classes that inherit from it.

Both Dog and Cat get everything public in Animal, so shared code lives in one place. Fix a bug in Animal once, and every derived class is fixed too.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers