Skip to main content
Be Bitwise
C++Classes & OOP

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:

cpp
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.

Try itPut virtual in front of Shape::area and run again, then add override to Circle::area and misspell it as aera to read the error.
C++ (GCC 9.2.0)

Virtual Functions

The virtual keyword enables dynamic dispatch:

cpp
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!
}
Key Concept

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:

cpp
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:

cpp
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.

cpp
Circle c(5.0); // say c lives at 0x7ffc3000
const Shape &s = c;
double a = s.area();
  1. The object. c is 16 bytes. Offset 0 holds the vptr, which the constructor set to the address of Circle's vtable, say 0x403d20. Offset 8 holds radius, 5.0.
  2. The table. Circle's vtable is a read-only array of function pointers, one per virtual function, in declaration order. Slot 0 (0x403d20) points to Circle::area. Slots 1 and 2 hold two flavours of destructor: one that only destroys and one that destroys and then frees the memory, for delete.
  3. The call. The compiler only knows s refers to some Shape. It emits: load 8 bytes from the object's address (0x7ffc3000) to get the vptr, 0x403d20; load the pointer in slot 0 at 0x403d20 + 0; call it, with this set to 0x7ffc3000.
  4. The result. That pointer is Circle::area, which reads radius at this + 8 and 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.

cpp
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?
c
Shape
Circle

Inside 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:

cpp
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.