Inheritance and polymorphism

Building classes on other classes, choosing the right function while the program runs with virtual functions, and describing abilities with abstract classes and interfaces.

About 10 hours of study

Learning objectives

Lessons

  1. 1

    Inheritance

    A derived class is a base class plus more: shared code in one place, protected members, and the order constructors and destructors run.

  2. 2

    Virtual functions and polymorphism

    A virtual function call picks the version for the object's real class, so one loop over base pointers works for every kind of object.

  3. 3

    Abstract classes and interfaces

    A pure virtual function (= 0) makes a class abstract: a promise that every derived class keeps, and a way to write interfaces.

Module practice

Module quiz

1. Building a derived object runs which constructor first?
2. Which relationship suits inheritance?
3. Where can a protected member of a base class be used?
4. Shape* s = new Circle(1); and area() is virtual. Which version does s->area() run?
5. What does override do on a derived member function?
6. A class overrides only one of its base class's two pure virtual functions. What is it?
7. Animal* p = new Dog(); delete p; and ~Animal is not virtual. What is the problem?

‹ Static members and operatorsTemplates and the standard library ›