C++ · Intermediate level

Intermediate level · Module 2 of 6 · 15 guided hours

Inheritance and Virtual Functions

Use inheritance for is-a relationships, virtual functions for runtime polymorphism and abstract base classes for interfaces, avoiding slicing and leaks.

Learning objectives

  • Derive classes and control access
  • Use virtual functions, override and abstract base classes
  • Avoid object slicing and give base classes virtual destructors

Topics

  • public inheritance
  • protected members
  • virtual and override
  • pure virtual functions
  • virtual destructors
  • object slicing
  • composition

Lessons

  1. Lesson 1 Inheritance in C++

    Derive classes from a base class, call base constructors and control access with public, protected and private.

    base and derived classpublic inheritanceprotectedbase constructor call

  2. Lesson 2 Virtual Functions and Abstract Classes

    Use virtual functions and override for runtime polymorphism, and pure virtual functions to define interfaces.

    virtualoverridepure virtual = 0dynamic dispatch

  3. Lesson 3 Virtual Destructors and Object Slicing

    Avoid two classic polymorphism bugs: deleting through a base pointer without a virtual destructor, and slicing derived objects.

    virtual destructorobject slicingpass by referencestd::unique_ptr<Base>

Practical activity

Model clinic staff (doctor, nurse, cleaner) with a base class and virtual monthlyPay(), and process a vector of std::unique_ptr<Staff>.

Expected outcomes

  • Correct polymorphic class hierarchies
  • Awareness of slicing and destructor pitfalls

Assessment

Code review against a checklist (override, virtual destructor, no slicing) plus a short practical extension.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.