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.
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 andSquare s(3)at 0x7010, one cell per field, with its offset. Blue cells are theShapepart, the green cell is the field the subclass adds. - Vtables: one table per class. Slot 0 is
area, slot 1 isdraw. - 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
intis 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)
Not virtual: p->name() | Virtual: p->area() | |
|---|---|---|
| Chosen | at compile time | at run time |
| Chosen by | the pointer's type | the object's class, through its vptr |
| Instructions | call 0x1080 | vptr = *p; fn = vptr[0]; call fn |
| Memory loads | 0 | 2 |
| Kind of call | direct | indirect |
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:
| Offset | Size | Content | Comes from |
|---|---|---|---|
| +0 | 8 | vptr = 0x3020 | added by the compiler, because Shape has virtual functions |
| +8 | 4 | id = 1 | Shape |
| +12 | 4 | r = 2 | Circle |
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.
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 markedfinal, 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.