Virtual functions & the vtable
The object carries a hidden pointer that decides which function runs.
Before you start
**Polymorphism** is the idea that different types can respond to the same call in their own way — a Dog and a Cat both understand speak(), but you get "woof" from one and "meow" from the other.
C++ implements this with **virtual functions**. When a method is declared virtual, the compiler doesn't hard-code which version to call. Instead, each object carries a hidden pointer (vptr) to a table (vtable) that lists which override to use.
This lesson makes the vtable visible: you'll see the hidden pointer inside each object, watch it lead to the correct function, and understand why virtual calls cost one extra memory read.
Stack
This is why a class with virtual functions is bigger than the sum of its members — usually by one pointer.
Step 1 of 7. Two objects, two layouts. `Circle` holds a `double r`; `Square` holds a `double side`. Different types, different sizes of data. But look at the first member of each: a pointer nobody declared. Because `Shape` has a virtual function, the compiler inserts a hidden `__vptr` at the start of every object in the hierarchy.
Step 01 / 07
Two objects, two layouts
Circle holds a double r; Square holds a double side. Different types, different sizes of data.
But look at the first member of each: a pointer nobody declared. Because Shape has a virtual function, the compiler inserts a hidden __vptr at the start of every object in the hierarchy.
#include <cstdio>struct Shape { virtual double area() const { return 0; } virtual ~Shape() = default;};struct Circle : Shape { double r; Circle(double r) : r(r) {} double area() const override { return 3.14159 * r * r; }};struct Square : Shape { double side; Square(double s) : side(s) {} double area() const override { return side * side; }};void report(const Shape &s) { printf("%f\n", s.area()); // which area()?}int main() { Circle c(2.0); Square q(3.0); report(c); report(q); return 0;}