Skip to main content
Module 6 · Lesson 2 of 214/26 in the course~16 min
Module lessons (2/2)

Polymorphism and virtual functions

Lesson preview5 hands-on exercises readyCourse C++ · Module 6 — Inheritance and Polymorphism

Resolve methods at runtime using virtual and override, virtual destructors, and pure abstract classes.

What you'll learn in this lesson

  • Enable late binding via virtual in the base and verify signatures with override in the subclasses.
  • Understand why a polymorphic base class must always have a virtual destructor (virtual ~Base() = default;).
  • Design pure abstract interfaces (= 0) and prevent unwanted extension with final.

Overview

Without virtual, calling a method via a Base* pointer always invokes the base class function (static binding). With virtual, the program solves the actual function of the real object at runtime thanks to the vtable.

Put virtual on the method in the base class and override at the end of the signature in the derivative. The compiler rejects the code if you miss a parameter or forget const on the override!

Sections covered in this lesson

  1. 11. Functions virtual and override
  2. 22. Polymorphic Call Via Reference or Smart Pointer
  3. 33. Mandatory Virtual Destroyer (virtual ~Base())
  4. 44. Pure Abstract Classes (= 0) and Keyword final
  5. 5Practical exercises
  6. 6Check for understanding
Pro Lesson · Module 6 — Inheritance and Polymorphism

Unlock "Polymorphism and virtual functions" and the full Course C++ curriculum

Resolve methods at runtime using virtual and override, virtual destructors, and pure abstract classes.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course C++ plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.