Polymorphism & Virtual Functions
Polymorphism lets one piece of code juggle objects of different types through a shared interface. C++ does it with virtual functions.
The Problem
Without virtual functions, the base class method is always called:
class Shape {public: double area() const { return 0; }};
class Circle : public Shape { double radius;public: Circle(double r) : radius(r) {} double area() const { return 3.14159 * radius * radius; }};
void print_area(const Shape &s) { std::cout << s.area() << std::endl; // Always calls Shape::area()!}See it for yourself. The second line prints 0 for a circle of radius 2, because print_area only knows it has a Shape.
Virtual Functions
The virtual keyword enables dynamic dispatch:
class Shape {public: virtual double area() const { return 0; } virtual ~Shape() = default; // base used polymorphically: virtual destructor};
class Circle : public Shape { double radius;public: Circle(double r) : radius(r) {} double area() const override { return 3.14159 * radius * radius; }};
void print_area(const Shape &s) { std::cout << s.area() << std::endl; // Now calls the correct version!}virtual tells the compiler to pick the function at runtime, based on the actual type of the object rather than the declared type of the pointer or reference holding it. override is your safety net — the compiler checks you really are overriding a virtual.
Pure Virtual Functions (Abstract Classes)
A pure virtual function has no implementation:
class Shape {public: virtual double area() const = 0; // pure virtual - must be overridden virtual ~Shape() = default;};A class with pure virtuals is abstract — you can't instantiate it. What you've defined is an interface every shape has to honour.
Virtual Destructors
Any base class you delete through a base pointer needs a virtual destructor:
Shape *s = new Circle(5.0);delete s; // Without virtual destructor, Circle's destructor won't run!Skip virtual ~Shape() and deleting through a base pointer fires only Shape's destructor. Whatever resources Circle was holding stay leaked.
How It Works: vtable
Every class with virtual functions earns itself a vtable — a table of function pointers. Each object carries a hidden pointer to its class's vtable. A virtual call walks the table and dispatches to the right function.
Follow one call, s->area(), for each element of the shapes vector further down, which holds a Circle and a Rectangle. The call site runs the same instructions both times: load the object's vptr, load the area slot from that table, call it. Only the table differs.
Worked Example: One Virtual Call, Step by Step
Take the Shape from the Virtual Functions section, with area declared first and the destructor second, and a Circle of radius 5.0. This is how GCC and Clang lay it out on x86-64 under the Itanium C++ ABI, which Linux and macOS both use. Addresses are illustrative.
Circle c(5.0); // say c lives at 0x7ffc3000const Shape &s = c;double a = s.area();- The object.
cis 16 bytes. Offset 0 holds the vptr, which the constructor set to the address ofCircle's vtable, say0x403d20. Offset 8 holdsradius, 5.0. - The table.
Circle's vtable is a read-only array of function pointers, one per virtual function, in declaration order. Slot 0 (0x403d20) points toCircle::area. Slots 1 and 2 hold two flavours of destructor: one that only destroys and one that destroys and then frees the memory, fordelete. - The call. The compiler only knows
srefers to someShape. It emits: load 8 bytes from the object's address (0x7ffc3000) to get the vptr,0x403d20; load the pointer in slot 0 at0x403d20 + 0; call it, withthisset to0x7ffc3000. - The result. That pointer is
Circle::area, which readsradiusatthis + 8and returns 3.14159 × 5.0 × 5.0 ≈ 78.54.
A Rectangle goes through the same three instructions. Its vptr leads to a different table whose slot 0 holds Rectangle::area, so nothing at the call site has to know which shape it's dealing with. Virtual functions and dispatch shows the real assembly.
That's the price of polymorphism: one pointer per object, one indirection per virtual call. Most of the time it's lost in the noise. The real cost shows up in hot loops, where a virtual call usually can't be inlined.
Virtual Calls During Construction
The vptr doesn't hold its final value from the start. While Shape's constructor runs, the Circle part doesn't exist yet, so the object's vptr points to Shape's vtable. Circle's constructor switches it over when its turn comes.
class Shape {public: Shape() { std::cout << name() << std::endl; } virtual const char *name() const { return "Shape"; } virtual ~Shape() = default;};
class Circle : public Shape {public: Circle() { std::cout << name() << std::endl; } const char *name() const override { return "Circle"; }};
Circle c;Predict: what does Circle c; print?
ShapeCircleInside Shape(), the object is still only a Shape, and the language says a virtual call there goes to Shape's version. That's deliberate: Circle::name could otherwise read Circle members that haven't been initialised yet. Destructors work the same way in reverse. Once ~Circle finishes, a virtual call from ~Shape gets Shape's version. If name were pure virtual in Shape, calling it from the constructor would be undefined behaviour; in practice the program usually aborts with a message such as "pure virtual method called".
Polymorphic Containers
Virtual functions let you store mixed types in a container:
std::vector<std::unique_ptr<Shape>> shapes;shapes.push_back(std::make_unique<Circle>(5.0));shapes.push_back(std::make_unique<Rectangle>(3.0, 4.0));
for (const auto &s : shapes) { std::cout << s->area() << std::endl;}Every element dispatches to its own area(). The vector holds unique_ptrs rather than Shapes by value, because a std::vector<Shape> would slice every Circle down to a Shape (and won't even compile once Shape is abstract). The unique_ptr deletes each shape through a Shape *, which is why the virtual destructor matters here.