Skip to content

Module 6 · Inheritance and Polymorphism — topic 4 of 5

Virtual Functions and the vtable

How virtual dispatch works under the hood with vtables and vptrs, virtual destructors, pure virtual functions and the cost of virtual calls.

Beginner 14 min read·Lesson 25 of 40 in C++ Programming

Learning objectives

  • Explain vtables and vptrs
  • Use virtual destructors correctly
  • Predict which function runs in constructors, destructors and through slicing

Definition

A virtual function is a member function declared with virtual whose call through a base pointer or reference is resolved at run time to the most-derived override, typically implemented with a per-class table of function pointers (vtable) and a hidden pointer in each object (vptr).

Introduction

How does shape->area() know to call Circle::area? Most compilers give each polymorphic class a hidden table of function pointers — the vtable — and each object a hidden pointer to its class's table. A virtual call reads that pointer and jumps through the table.

Why it matters

Knowing the mechanism explains the costs (an extra pointer per object, an indirect call) and the rules (no virtual dispatch in constructors).

Virtual destructors are a frequent interview question and a real source of leaks.

Detailed explanation

Each class with virtual functions has a vtable listing the addresses of its final overriders. Each object carries a vptr set by the constructor of each class in turn.

A non-virtual call is bound at compile time (early binding); a virtual call through a pointer or reference is bound at run time (late binding).

Virtual destructor: deleting a derived object through a Base* calls the derived destructor only if the base destructor is virtual; otherwise behaviour is undefined (typically the derived part leaks).

During construction and destruction, virtual calls resolve to the class currently being constructed/destroyed.

sizeof a class with virtual functions includes the vptr (usually 8 bytes on 64-bit systems).

Syntax

C++
class Base {
public:
virtual ~Base() = default; // essential for polymorphic bases
virtual void run() = 0; // pure virtual
void helper() { run(); } // non-virtual function calling virtual
};
  • One virtual in the base makes the function virtual in all derived classes.
  • Pure virtual functions may still have a definition.
  • Abstract classes still need virtual destructors.

Code examples

Virtual vs non-virtual

C++
#include <iostream>
struct Base {
virtual ~Base() = default;
void plain() const { std::cout << "Base::plain\n"; }
virtual void virt() const { std::cout << "Base::virt\n"; }
};
struct Derived : Base {
void plain() const { std::cout << "Derived::plain\n"; }
void virt() const override { std::cout << "Derived::virt\n"; }
};
int main() {
Derived d;
const Base& b = d;
b.plain();
b.virt();
return 0;
}
Output
Base::plain
Derived::virt

The cost of a vptr

C++
#include <iostream>
struct Plain { int x; };
struct Poly { int x; virtual ~Poly() = default; };
int main() {
std::cout << sizeof(Plain) << ' ' << (sizeof(Poly) > sizeof(Plain)) << '\n';
return 0;
}
Output
4 1

More examples

Virtual destructors and calls during construction

C++
#include <iostream>
#include <memory>
struct Base {
Base() { hello(); }
virtual ~Base() { std::cout << "~Base\n"; }
virtual void hello() const { std::cout << "hello from Base\n"; }
};
struct Derived : Base {
Derived() { hello(); }
~Derived() override { std::cout << "~Derived\n"; }
void hello() const override { std::cout << "hello from Derived\n"; }
};
int main() {
std::unique_ptr<Base> p = std::make_unique<Derived>();
p->hello();
p.reset(); // virtual destructor: both destructors run
return 0;
}
Output
hello from Base
hello from Derived
hello from Derived
~Derived
~Base

Step-by-step explanation

  • While Base's constructor runs, the object is a Base, so hello() calls the Base version.
  • In Derived's constructor the vptr now points to Derived's table.
  • After construction, p->hello() dispatches to Derived.
  • reset() deletes through Base*; the virtual destructor ensures ~Derived runs first.

Expected output

Running “Virtual destructors and calls during construction” prints exactly:

TextOutput
hello from Base
hello from Derived
hello from Derived
~Derived
~Base

Practical applications

  • Every polymorphic framework class (QObject, std::exception) has a virtual destructor.
  • Game engines avoid virtual calls in very hot loops for performance.
  • COM and plugin ABIs are built on vtable layouts.

Best practices

  • Make destructors of polymorphic base classes public and virtual.
  • Don't call virtual functions from constructors or destructors expecting derived behaviour.
  • Use final on classes not meant for derivation; compilers can then devirtualise calls.

Common mistakes

Non-virtual destructor in a polymorphic base

Avoid

struct Base { virtual void f(); ~Base(); };
Base* b = new Derived; delete b;

Prefer

struct Base { virtual void f(); virtual ~Base() = default; };

Without a virtual destructor, delete b doesn't run Derived's destructor — undefined behaviour and typically a leak.

Expecting dispatch through a value

Avoid

void show(Base b) { b.virt(); }

Prefer

void show(const Base& b) { b.virt(); }

By value, the argument is sliced to a Base, so Base::virt runs.

Important notes

  • The vtable mechanism is not specified by the C++ standard; it is the near-universal implementation technique.
  • A class with no virtual functions has no vptr, so simple structs cost nothing extra.

Key takeaways

  • Virtual calls go through the object's vptr to its class vtable.
  • Base classes used polymorphically need virtual destructors.
  • Inside constructors/destructors, virtual calls don't reach derived overrides.

Try it yourself

  1. 1
    Remove virtual from the destructor in the example, run with -fsanitize=address, and observe what changes.
  2. 2
    Print sizeof for classes with zero, one and three virtual functions and explain the results.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

6 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhy should a polymorphic base class have a virtual destructor?
  • BeginnerHow do most compilers implement virtual function calls?
  • ModerateWhat is printed?
Practise this topic