The idea: the object knows its class

In C++ a pointer of type Shape* may point to a Circle or a Square. When the code says p->area(), which area should run? If area is virtual, the answer comes from the object, not from the pointer's type. Every object of a class with virtual functions carries a hidden pointer, the vptr. It points to a table of function addresses made once for the object's class, the vtable. The call reads the vptr, reads one slot of the table, and calls the address it finds there.

Four columns. The pointer p holds 0x7000 and has type Shape*. Arrow 1 goes to the object, a Circle at 0x7000 with three cells: vptr = 0x3020, id = 1, r = 2. Arrow 2 goes from the vptr to the vtable for Circle at 0x3020, with slot 0 area and slot 1 draw. Arrow 3 goes from slot 0 to the function Circle::area; slot 1 points to Circle::draw
A virtual call is three hops: the pointer, the object's vptr, then the slot of the class's vtable.

How to read the page

  • Call site: the pointer, the call, and the instructions the compiler emitted for it. Below it is the source of the three classes.
  • Objects: Circle c(2) at 0x7000 and Square s(3) at 0x7010, one cell per field, with its offset. Blue cells are the Shape part, the green cell is the field the subclass adds.
  • Vtables: one table per class. Slot 0 is area, slot 1 is draw.
  • Code: every function, once, with its address.
  • Yellow marks what the current call touched; an orange box is a value on its way. The call log counts memory loads.
  • The addresses are made up but keep the real sizes: pointers are 8 bytes, an int is 4.

Static and dynamic binding

Binding means choosing the function a call will run. For a function that is not virtual, such as name(), the compiler chooses while it compiles. It only looks at the pointer's type: through a Shape* it emits a direct call to Shape::name, even when the object is a Circle and Circle has its own name(). This is static binding. (Demo: a non-virtual call)

For a virtual function the compiler cannot choose, because the object's class is only known while the program runs. It emits code that asks the object. This is dynamic binding. (Demo: one virtual call, hop by hop)

Left, p->name(), not virtual: one box 'call 0x1080' with an arrow straight to Shape::name; it uses the pointer's type, the object is never read, 0 memory loads and 1 direct call. Right, p->area(), virtual: p, then load 1 to the vptr, load 2 to slot 0, then a call to Circle::area; it uses the object's class, 2 memory loads and 1 indirect call
A non-virtual call is one direct jump; a virtual call first reads the vptr and then a vtable slot.
Not virtual: p->name()Virtual: p->area()
Chosenat compile timeat run time
Chosen bythe pointer's typethe object's class, through its vptr
Instructionscall 0x1080vptr = *p; fn = vptr[0]; call fn
Memory loads02
Kind of calldirectindirect

The same line p->area() runs Circle::area (12.56) when p points to c and Square::area (9) when it points to s. The line did not change; the vptr it read did. (Demo: same call line, two objects)

Object layout under single inheritance

A Circle object is 16 bytes:

OffsetSizeContentComes from
+08vptr = 0x3020added by the compiler, because Shape has virtual functions
+84id = 1Shape
+124r = 2Circle

The base part comes first, and the subclass's fields are added after it. So the first 12 bytes of a Circle look exactly like a Shape, and a pointer to the Circle can be used as a Shape* without changing its value. Without virtual functions the object would be 8 bytes. The price of virtual functions is one vptr in every object; the vtable itself exists once per class. (Demo: object layout)

How a vtable is built

The base class fixes the slot numbers: area is slot 0 and draw is slot 1, in the order they are declared. A subclass's vtable starts as a copy of the base's table. Each function the subclass overrides replaces the address in its slot. A function it does not override keeps the base's address: Square has no draw, so slot 1 of its table still holds Shape::draw.

The vtable for Shape has slot 0 area, the pure virtual stub, and slot 1 draw, Shape::draw. An arrow to the vtable for Circle: both slots replaced, by Circle::area and Circle::draw. An arrow to the vtable for Square: slot 0 replaced by Square::area, slot 1 kept as Shape::draw
A subclass's vtable is the base's table with the overridden slots replaced; the slot numbers never change.

Because the slot numbers are the same in every table, the calling code never needs to know which subclass it has. It always reads slot 0 for area.

Pure virtual slots and constructors

virtual double area() = 0; is a pure virtual function: Shape declares the slot but has no function for it. A class with a pure virtual function is abstract, and the compiler refuses Shape x;. Its vtable still exists, and slot 0 points to a small stub (__cxa_pure_virtual in GCC and Clang) that stops the program with "pure virtual method called".

That table is used for a short time. The constructor sets the vptr. When Circle c(2) is built, Shape's constructor runs first and points the vptr at Shape's table; then Circle's constructor overwrites it with Circle's table. So a virtual call made inside the base constructor does not reach the subclass's function. (Demo: the constructor sets the vptr)

What override does

A function overrides a virtual function only when its name and parameters match exactly. If Circle spells it virtual void drow(), the compiler sees a new virtual function. It gets a new slot 2, slot 1 keeps Shape::draw, and p->draw() on a circle quietly runs the base function.

The keyword override (C++11) asks the compiler to check: "this must replace a slot of a base class". With void drow() override; the build stops with an error. The keyword adds no code and no slot. The vtable of a correct class is the same with or without it. (Demo: a misspelled override)

What it costs

  • Space: 8 bytes per object for the vptr, and one small table per class.
  • Time: two extra loads and an indirect call. The loads are usually in the cache. The larger cost is that the compiler cannot inline a call when it does not know the target.
  • When the compiler can prove the object's class, for example a call on a local object c.area() or on a class marked final, it calls the function directly. This is called devirtualization.

See also Inheritance vs composition for when to use a class tree at all, Strategy and Factory Method for a design built on virtual calls, Stack vs heap in C for where objects live, and How a C++ program is compiled and linked for where the vtables and functions end up in the program file.

See also Overloading vs overriding in Java for how javac picks an overload from static types before the run-time dispatch shown here.

See also Struct padding and alignment in C for how the fields after the vptr are placed and padded.

What the page leaves out

A real Itanium ABI vtable has two more entries in front of slot 0, the offset to the top of the object and a pointer to the class's type information (RTTI), and the vptr points just past them. The page leaves out virtual destructors (which take two slots), multiple and virtual inheritance (several vptrs in one object, pointer adjustment and thunks), covariant return types, pointers to member functions, and how the linker keeps only one copy of each vtable. The MSVC ABI lays things out a little differently. The C++ standard itself does not require vtables; it only describes the behaviour, and every major compiler implements it this way.

On the mind map

Open the Software Design mind mapSoftware DesignPrinciples: keep each change localPrinciplesDesign patterns: named fixes for common designsDesign patternsArchitecture: the shape of a whole appArchitectureEnterprise app patterns: logic, SQL, locks, money (PoEAA)Enterprise app patternsGit storage: content named by its hashGit storageGit branches & merging: pointers to commits, then mergeGit branches & mergingTesting: check code in isolationTestingSOLIDSOLIDfive rules so one change hits one classInheritance vs compositionInheritance vs compositionis-a locks the tree; has-a mixes partsVirtual calls, vtableobject → vptr → vtable slot → functionOverloading vs overridingOverloading vs overridingjavac: static types; JVM: receiver's classCoupling and cohesionCoupling and cohesionOne change should touch one moduleControl-flow coverageControl-flow coverage100% statements can still miss a bugBoundary Value TestingBoundary Value TestingBugs sit at class edges: test min−1 … max+1Condition Coverage and MC/DCCondition Coverage and MC/DCEach condition flips D alone: N+1 testsMutation testingMutation testingCoverage runs code; mutants test the assertsOpen the Software Design mind mapSoftware Designkeep each change localPrinciplesSOLIDSOLIDfive rules so one change hits one classInheritance vs compositionInheritance vs compositionis-a locks the tree; has-a mixes partsVirtual calls, vtableobject → vptr → vtable slot → functionOverloading vs overridingOverloading vs overridingjavac: static types; JVM: receiver's classCoupling and cohesionCoupling and cohesionOne change should touch one moduleControl-flow coverageControl-flow coverage100% statements can still miss a bugBoundary Value TestingBoundary Value TestingBugs sit at class edges: test min−1 … max+1Condition Coverage and MC/DCCondition Coverage and MC/DCEach condition flips D alone: N+1 testsMutation testingMutation testingCoverage runs code; mutants test the asserts
This page on the Software Design mind map · 38 pages in 7 branches · open it to see the whole map and test yourself in recall mode.