</>EmbeddedInterview

How do virtual functions work? What is a vtable?

MediumC++ for Embedded

Short answer: For each class with virtual functions, the compiler builds a vtable, a table in flash holding pointers to that class's implementations of each virtual function. Each object of such a class contains a hidden vptr that points to its class's vtable, set by the constructor. A virtual call loads the vptr, loads the function pointer from the right slot and calls it indirectly. The cost is one pointer of RAM per object, one vtable per class in flash, and an indirect call that prevents inlining (unless the compiler can devirtualise it).

#include <cstdio>

struct Sensor {
    virtual int read() = 0;               // pure virtual: interface
    virtual ~Sensor() = default;          // virtual destructor if deleted via base pointer
};

struct Tmp102 : Sensor { int read() override { return 25; } };
struct Bme280 : Sensor { int read() override { return 21; } };

int average(Sensor *const *s, int n)      // works with any sensor type
{
    int sum = 0;
    for (int i = 0; i < n; i++) sum += s[i]->read();   // ldr vptr; ldr [vptr, #slot]; blx
    return sum / n;
}

int main()
{
    Tmp102 a; Bme280 b;
    Sensor *list[] = { &a, &b };
    std::printf("%d\n", average(list, 2));   // 23
}

What a virtual call compiles to (conceptually)

struct Sensor_vtbl { int (*read)(struct Sensor *); void (*dtor)(struct Sensor *); };
struct Sensor { const struct Sensor_vtbl *vptr; };
/* s->read()  ==>  s->vptr->read(s) */

This is exactly the "struct of function pointers" pattern C drivers use (e.g. Linux file_operations), but generated and type-checked by the compiler.

Details interviewers ask

  • Calling a virtual function from a constructor or destructor calls the version of the class being constructed, not the derived one.
  • A base class with virtual functions that is deleted through a base pointer needs a virtual destructor, otherwise the derived destructor does not run (undefined behaviour).
  • final on a class or function lets the compiler devirtualise calls.
  • Multiple inheritance can add several vptrs per object and "thunks" to adjust this.
  • Abstract interfaces with pure virtual functions still need a vtable; on very small MCUs, consider CRTP (next question) when the type is known at compile time.