Virtual Functions &
Dynamic Dispatch
Learn how C++ decides which function to call at runtime using virtual functions, vtables, and polymorphism: the cornerstone of object-oriented design.
What is Polymorphism?
Polymorphism means "many forms." In C++, it lets you write code that works with a base class pointer or reference, yet automatically calls the correct function for the actual derived type at runtime.
Why Virtual Functions Matter
Imagine a drawing program with shapes: Circle, Rectangle, Triangle. You want one loop that tells every shape to draw itself, without knowing the exact type.
Key Vocabulary
The virtual Keyword
How Dynamic Dispatch Works
Static vs Dynamic Binding
| Static Binding | Dynamic Binding | |
|---|---|---|
| When resolved | Compile time | Runtime |
| Keyword needed | None (default) | virtual |
| Called through | Value or non-virtual call | Pointer or reference |
| Performance | Slightly faster (inlineable) | Small overhead (vtable lookup) |
| Flexibility | Fixed at compile time | Adapts to actual object type |
Pure Virtual Functions
Virtual Destructors
When you delete a derived object through a base pointer, the destructor must also use dynamic dispatch. Otherwise, the derived destructor never runs, causing resource leaks.
Step-by-Step Checklist
Example 1: Shape Hierarchy
Example 2: Polymorphic Container
Example 3: Without vs With Virtual
Inside the vtable
Common Mistakes
Summary Table
| Concept | What It Does | Key Detail |
|---|---|---|
| virtual | Enables dynamic dispatch | Place in base class declaration |
| override | Signals an override to the compiler | Catches signature mismatches |
| = 0 | Makes function pure virtual | Class becomes abstract |
| Virtual dtor | Correct destruction through base ptr | Prevents UB and leaks |
| vtable/vptr | Hidden mechanism for dispatch | One vtable per class, one vptr per object |
Question 1 of 5
What does the virtual keyword do when placed before a member function in a base class?
Question 2 of 5
Consider this code:
#include <iostream> class Base { public: void hello() { std::cout << "Base"; } }; class Derived : public Base { public: void hello() { std::cout << "Derived"; } }; Base* p = new Derived(); p->hello();
What does this program print?
Question 3 of 5
What happens if you delete a derived object through a base pointer and the base class lacks a virtual destructor?
Question 4 of 5
What does = 0 after a virtual function declaration mean?
Question 5 of 5
Which of the following best describes the purpose of the override keyword in a derived class?