Module lessons (2/2)
Polymorphism and virtual functions
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
virtualin the base and verify signatures withoverridein 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 withfinal.
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
- 11. Functions
virtualandoverride - 22. Polymorphic Call Via Reference or Smart Pointer
- 33. Mandatory Virtual Destroyer (
virtual ~Base()) - 44. Pure Abstract Classes (
= 0) and Keywordfinal - 5Practical exercises
- 6Check for understanding
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.