01 / 21

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.

C++

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.

Compile-time
Function overloading and templates: the compiler picks the right version before the program runs.
Runtime
Virtual functions: the program picks the right version while running, based on the actual object type.

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.

for (Shape* s : shapes) { s->draw(); // calls Circle::draw, Rect::draw, etc. }

Key Vocabulary

virtual
Keyword placed before a member function in the base class to enable runtime dispatch.
override
Keyword in the derived class that tells the compiler you intend to replace a virtual function.
vtable
A hidden table of function pointers the compiler generates for each class with virtual functions.
vptr
A hidden pointer inside every object that points to its class's vtable.
Dynamic Dispatch
The process where the program looks up the vptr → vtable → function pointer at runtime.

The virtual Keyword

#include <iostream> class Animal { public: virtual void speak() const { std::cout << "..." << "\n"; } }; class Dog : public Animal { public: void speak() const override { std::cout << "Woof!" << "\n"; } };

How Dynamic Dispatch Works

Dog object vptr → data members Dog vtable speak → Dog::speak eat → Animal::eat Dog::speak() prints "Woof!" 1. Object has vptr 2. vptr → class vtable 3. vtable → function Animal* p = new Dog; p->speak();

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

class Shape { public: virtual double area() const = 0; // pure virtual virtual ~Shape() = default; };
= 0
Makes the function pure virtual: no implementation in the base class. Derived classes must override it.
Abstract Class
A class with at least one pure virtual function. You cannot instantiate it directly.

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.

class Base { public: virtual ~Base() = default; // ✓ correct }; Base* p = new Derived(); delete p; // calls ~Derived(), then ~Base()

Step-by-Step Checklist

1
Identify shared behavior. Find a function that multiple derived classes need to implement differently.
2
Declare it virtual in the base. Add the virtual keyword before the return type.
3
Add a virtual destructor. Always include virtual ~Base() = default; in your base class.
4
Override in each derived class. Use the override keyword and match the exact signature.
5
Use base pointers or references. Store derived objects via Base* or Base& to enable dynamic dispatch.

Example 1: Shape Hierarchy

class Shape { public: virtual double area() const = 0; virtual ~Shape() = default; }; class Circle : public Shape { double r; public: Circle(double radius) : r(radius) {} double area() const override { return 3.14159 * r * r; } };

Example 2: Polymorphic Container

#include <iostream> #include <vector> #include <memory> // Assume Shape and Circle are defined as before class Rect : public Shape { double w, h; public: Rect(double width, double height) : w(width), h(height) {} double area() const override { return w * h; } }; std::vector<std::unique_ptr<Shape>> shapes; shapes.push_back(std::make_unique<Circle>(5.0)); shapes.push_back(std::make_unique<Rect>(3.0, 4.0)); for (const auto& s : shapes) { std::cout << s->area() << "\n"; // prints 78.53975, then 12.0 }

Example 3: Without vs With Virtual

// WITHOUT virtual #include <iostream> class A { public: void greet() { std::cout << "A\n"; } }; class B : public A { public: void greet() { std::cout << "B\n"; } }; A* p = new B(); p->greet(); // prints "A" ← static binding!
// WITH virtual #include <iostream> class A { public: virtual void greet() { std::cout << "A\n"; } }; // Class B is the same as above A* p = new B(); p->greet(); // prints "B" ← dynamic dispatch!

Inside the vtable

Animal vtable speak → Animal::speak eat → Animal::eat Dog vtable speak → Dog::speak eat → Animal::eat Animal obj vptr Dog obj vptr Each class has its own vtable. Overridden slots point to the derived version.

Common Mistakes

✕ Forgetting virtual
Without virtual in the base, the base version always runs through a base pointer: no polymorphism.
✕ No virtual destructor
Deleting a derived object through a base pointer without a virtual destructor is undefined behavior.
✕ Signature mismatch
If the derived function has a different signature, it hides the base version instead of overriding. Use override to catch this.

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?