C++
Module 16: PolymorphismIntermediate55 min read

Virtual Functions, Abstract Classes, vtable Internals & Virtual Destructors

Master runtime polymorphism with virtual functions, override, final, pure virtual interfaces, vptr/vtable internals, virtual destructors, and dynamic_cast.

Key Takeaways & Core Concepts
  • Compile-Time: Function overloading, operator overloading, templates.
  • Runtime: Virtual functions dispatched through base pointers/references.
  • Pure Virtual (`= 0`): Makes the class abstract (cannot be instantiated).
  • `override` & `final` (C++11): Catch signature mismatches at compile time and prevent further overriding.

1. Static vs. Dynamic Polymorphism

  • Compile-Time: Function overloading, operator overloading, templates.
  • Runtime: Virtual functions dispatched through base pointers/references.
1. Abstract Interface, override & dynamic_cast
1#include <iostream>
2#include <memory>
3
4class Payment {
5public:
6 virtual void pay(double amt) const = 0;
7 virtual ~Payment() = default;
8};
9
10class UpiPayment final : public Payment {
11public:
12 void pay(double amt) const override { std::cout << "Paid Rs." << amt << " via UPI\n"; }
13};
14
15int main() {
16 std::unique_ptr<Payment> p = std::make_unique<UpiPayment>();
17 p->pay(499.0);
18 return 0;
19}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
19 lines
Note: `UpiPayment` is marked `final` and overrides `pay` safely.

2. `vtable` & `vptr` Internals

Each polymorphic class has a compiler-generated vtable (array of function pointers), and every instance contains a hidden vptr pointing to its class's vtable. Calling basePtr->draw() performs one pointer indirection at runtime.

3. Pure Virtuals, `override`, `final`, Virtual Destructors & `dynamic_cast`

  • Pure Virtual (`= 0`): Makes the class abstract (cannot be instantiated).
  • `override` & `final` (C++11): Catch signature mismatches at compile time and prevent further overriding.
  • Virtual Destructor: Mandatory in polymorphic base classes (virtual ~Base() = default;) so delete basePtr; invokes the derived destructor!
  • `dynamic_cast<Derived>(basePtr)**: Safely downcasts at runtime (returns nullptr` on failure).
Practice & AssessmentC++ Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)