Careers[careers]

How C++ Virtual Functions Pick the Right Code at Runtime

Abstract

A virtual function in C++ lets a derived class replace a base-class operation, with the implementation chosen at runtime according to the object’s actual type when called through a base pointer or reference. Use `override` to catch signature mistakes, `final` to prevent further overrides, and a virtual destructor when deleting derived objects through a base pointer; pass polymorphic objects by reference or pointer to avoid slicing. Virtual dispatch makes mixed types easier to extend and use uniformly, but adds memory and call overhead, so measure before choosing alternatives such as templates

A pointer rod selects a brass cylinder, revealing a specific diagram card while others remain faint.
Figure 1 — A pointer rod selects a brass cylinder, revealing a specific diagram card while others remain faint.

Think of a universal remote with one Play button. The same press gets a different response from the TV, the speaker, and the game console.

That’s the idea behind a virtual function in C++: you call through a base class pointer or reference, and the object that actually exists decides which code runs.

Under the hood, a virtual table (a per-class list of function pointers) picks the right entry at run time.

We’ll cover how dispatch works, how to write virtual functions safely with override and final, what they cost, and the mistakes that break them, with every rule dated to its standard and compiler.

Understanding C++ Virtual Functions and Their Purpose

A virtual function lets a base class declare an operation that derived classes can replace, with the right version chosen at runtime. Here’s how that works and where we see it pay off.

How derived classes override a base function

A derived class provides its own version of a member function declared in the base class. You mark the base function virtual, which tells the compiler to pick the version by the object’s actual type, not the type of the pointer or reference you used.

This is runtime polymorphism: one call, different behavior depending on the object. The choice is made through dynamic binding, at runtime rather than at compile time.

Using base pointers to handle mixed objects

The real payoff shows up when you hold a base pointer to a derived object. For example, a developer building a drawing app can keep an array of base pointers (Shape*) to circles, rectangles and text boxes, then call draw() on each in one loop.

You don’t write a type check. The correct override runs for every element, because the call depends on the object, not the pointer. That lets you process mixed objects uniformly, and a new shape means writing a new class, not editing the loop.

Where virtual functions fit in real designs

Virtual functions shine when you encapsulate behavior in classes and decouple an interface from its implementation.

For example, a game programmer defines an Enemy base class with a virtual attack() function, and goblins, dragons and turrets each override it.

The spawn code and combat system depend only on Enemy, so a designer can add a new monster without touching either one.

Two patterns build on this. In a Factory, one function decides which derived class to create and returns a base pointer, so callers never name the concrete type.

In a Strategy, an object holds a swappable behavior, such as a pathfinding policy, and you replace it at runtime without rewriting the object that uses it.

Writing Virtual Functions the Right Way

Virtual functions look simple until a small typo quietly turns an override into a brand-new function. Here’s what to get right.

Rules to follow when declaring virtual functions

  • Declared in the base class. The base must declare the function virtual first.
  • Same signature in the derived class. Use the same name and parameter list. Change the parameters and you’ve written a new function that overrides nothing.
  • No virtual static functions. A static member has no object to dispatch through, so the language rejects it.
  • Access level and return type. The return type has to match, with one allowed exception: a covariant return type. The access level can differ, since access is checked against the type you call through.
  • Base version used if not overridden. Skip the override and calls land on the base implementation.
Top-down ink drawing of a master template plate with compatible and incompatible derived plates, illustrating precise fits and exclusions using steel blue and vermilion accents.
Figure 2 — Top-down ink drawing of a master template plate with compatible and incompatible derived plates, illustrating precise fits and exclusions using steel blue and vermilion accents.

Using override to catch mistakes

The override specifier marks an intentional override. According to a paper on transforming C++11 code to C++03, it indicates that a base-class virtual function is being overridden, and the compiler checks that the signature matches.

Since C++11, you write it after the parameter list:

void tick(float dt) override;

It’s optional, but we recommend it on every override. Override is less about adding a feature and more about asking the compiler to check your work. Consider a game engine programmer who renames the base update to tick.

Without override, the derived update compiles silently, and the base tick runs every frame. With override, the next build fails right at the mismatch.

Stopping further overrides with final

Mark a function final when a derived class must not replace it. Any attempt to override it is a compiler error, so the rule is enforced, not hoped for.

A team that ships a base Codec::encode with a fixed wire format can mark it final, and the build fails if a subclass tries to change the bytes.

Building abstract classes with pure virtual functions

A pure virtual function ends its declaration with = 0, as in virtual void draw() = 0;. A class with one is abstract: you can’t create an object of it, and each derived class must override draw() before you can.

Consider a UI toolkit whose Widget base declares draw() = 0. Buttons, sliders, and labels each supply their own draw(), so the toolkit can hold a list of Widget pointers without caring which is which.

Miss one override, and the build fails when you try to create that class. Study interface design next to go deeper.

Constructors cannot be virtual but destructors can

Constructors can’t be virtual, since a constructor runs to create the object and there’s nothing yet to dispatch through. Destructors can be, and should be when you delete through a base pointer.

A virtual destructor makes that delete run the derived destructor too. Without it, the derived class’s cleanup can be skipped and whatever it owns leaks.

Declaring one also brings the rule of five into play: think through the destructor, copy and move constructors, and copy and move assignment operators together.

Derived classes stay virtual without the keyword

Repeating virtual in a derived class is optional. An overriding function stays virtual automatically, and so does any intermediate class’s function that overrides the base.

Think of a teammate coming from C who sees virtual on the base and wonders whether the derived copy needs it too. It doesn’t. Let override carry the intent, and leaving the keyword off doesn’t change the behavior.

How the Compiler Picks Which Function Runs

Ever called draw() through a base pointer and wondered which version ran? The answer depends on when the compiler makes that choice and on what the object really is.

Early versus late binding of calls

By default, C++ uses early binding. The compiler picks the function at compile time from the type written in the code, so nothing is looked up while the program runs.

Virtual functions switch to late binding: the choice happens at runtime, and the actual object type decides which override runs, not the pointer or reference type you called through.

The lookup starts at the object’s real class and works up the inheritance tree to the closest definition.

Picture a gameplay programmer whose Enemy base class declares a virtual attack(), with Goblin and Dragon overriding it. A loop over std::vector<Enemy*> calls attack() on each pointer, and every monster strikes its own way.

Adding a new monster means adding a class, not editing the loop.

Top-down sketch of a game design notebook showing a loop for attacking various enemies, including a goblin, dragon, and slime.
Figure 3 — Top-down sketch of a game design notebook showing a loop for attacking various enemies, including a goblin, dragon, and slime.

How the vtable and vptr work

The compiler implements this with a virtual table (vtable), a static array of function pointers whose entries point at that class’s virtual functions.

Each object of a class with virtual functions gets a hidden virtual pointer (vptr) that leads to its class’s vtable. The compiler adds both, so you never write either one.

Let’s see how a virtual call uses them. It runs three steps:

  1. Follow the object’s vptr to its vtable.
  2. Index into the table to fetch the right function pointer.
  3. Call through that pointer.

That’s an extra memory read and an indirect jump on every call. Cheap, but not free. The vtable layout is implementation-defined, covering the order of entries and where the vptr sits, so your code shouldn’t depend on either.

Mistakes That Break Virtual Functions

Two slips cause most of the trouble with virtual functions, the functions a derived class can replace, with the right version picked at run time. Here’s how each one plays out, and how we’d fix it. Neither crashes, so both can sit in a codebase for years.

Forgetting virtual hides the derived version

Picture a firmware developer who adds a FastCodec class beside an existing Codec base. The base’s encode() isn’t marked virtual, so the new function doesn’t override it. Instead it hides the base version, a behavior called name hiding.

When the code holds a Codec*, the old encode() runs and the new encoder never executes. Nothing crashes. The output is just quietly wrong.

The same pointer also can’t reach anything that exists only in the derived class. If FastCodec adds setBlockSize(), then Codec* c can’t call c->setBlockSize(), because the compiler checks names against the pointer’s declared type.

Mark the base function virtual, and the derived version overrides it, so the call follows the object’s real type. One keyword, and the right function runs.

A related trap is calling a virtual function from a constructor or destructor. While a base class is being built or torn down, the object’s still just the base class, so the call runs the base version even when a derived class overrides it.

Why passing by value slices off data

Consider a game engine programmer whose draw(Shape s) takes shapes by value. Pass in a Circle, and the function receives a plain Shape copy: the radius is chopped off, and Shape’s version of draw runs.

This is object slicing, and it silently drops both the derived data and the polymorphism.

The fix is one character: write Shape& instead of Shape, or pass a Shape*. The whole circle survives the call.

Benefits and Costs of Virtual Functions

Virtual functions buy flexibility, and they charge for it. Here’s the trade.

What you gain from virtual code

Consider a game engine team whose scene code calls draw() through a Renderer&. Adding a Vulkan backend leaves that code untouched, since it cares about what a renderer can do, not which one you’ve got.

  • Flexible, reusable code. Write logic once against the base interface.
  • Easier extension and maintenance. New derived classes don’t touch existing callers.
  • Code reusability. Shared behavior lives in one base class instead of being copied around.
  • Interchangeable derived objects. A test double can stand in for a real network client.
An engineer watches a pedestal keep a miniature world unchanged while interchangeable modules slide into its socket.
Figure 4 — An engineer watches a pedestal keep a miniature world unchanged while interchangeable modules slide into its socket.

Speed and memory costs to consider

Each class with virtual functions gets a vtable (a table of function pointers), and each object typically carries a hidden pointer to it. The bill has several parts:

  • Memory overhead. Every polymorphic object carries that extra pointer, so the cost grows with object count.
  • Runtime lookup overhead. A source on dynamic dispatch in object-oriented languages notes that virtual calls use dynamic dispatch, which can add runtime lookup overhead.
  • Calls can’t be inlined. The compiler often can’t know which override runs.
  • Harder optimization. The optimizer has less type information to work with.
  • Added code complexity. Hierarchies and overrides are more to read and review.
  • constexpr virtual. Since C++20, virtual functions can be declared constexpr, so dispatch can run during constant evaluation.

The cost isn’t always fixed. If the compiler can prove the exact dynamic type, it can devirtualize the call and inline it. Marking a class or an override final tells it no further override can exist.

When the cost matters, you have options. Templates fix the type at compile time rather than at run time.

std::variant holds one of a closed set of types, and CRTP (the curiously recurring template pattern) gives static polymorphism with no vtable. Measure before you rewrite.

Examples and Next Steps to Try

Reading about virtual functions only goes so far, so let’s run some code.

Code samples with animals, shapes, and battles

Start with a base class that declares a virtual function, then write a derived class that overrides it and prints the result through a base reference. Put an Animal, a Dog, and a Cat in one std::vector and loop over it.

The loop cares about what each element can do, not which class it came from.

Repeat the pattern with Shape, Circle, and Square, then build a battle with a Goblin and a Dragon. A game programmer adding a Troll writes one new class, and the battle loop stays untouched. Less code, same loop.

Prefer std::unique_ptr over raw pointers when you own these objects. It frees each one when its owner goes out of scope, so there’s no manual delete and no forgotten cleanup.

Growing a class hierarchy over time

Practice growing a hierarchy four ways:

  • Add depth to the core system: Move shared behavior into the base class, and let derived classes refine it.
  • Add breadth with new types: Introduce a Bird beside the Dog and Cat, and the loop picks it up unchanged.
  • Multi-level inheritance: Derive a GoblinShaman from Goblin, then check which override runs at each level.
  • Split across files: Give each class its own file so teammates can add types without opening the base.

Where to take your skills next

Four directions are worth your time next:

  • Design patterns: Study patterns such as Strategy, which swaps derived classes behind one base.
  • Abstract classes: Add a pure virtual function so the base becomes an abstract class and nobody can create a bare base object by mistake.
  • Refactor legacy code: Swap old enum tags for virtual calls, one class at a time.
  • Practice projects: Build a small text adventure where each room type is a derived class.

Virtual functions give you one call that works across many types, and the object’s real type decides the behavior. Mark overrides with override, use final when a class shouldn’t be extended, and weigh the per-call cost against what you gain.

Revisit these choices as your codebase grows. Check each feature against the standard and compiler your team actually builds with, and reach for alternatives when a fixed set of types is enough.

Used with care, virtual functions keep your design flexible and your code easy to change.

References

  1. Transforming C++11 Code to C++03 to Support Legacy Compilation Environments — doi.org (2024)
  2. Dynamic dispatch in object-oriented languages — digitalcollections.anu.edu.au (1994)

Questions

What is the virtual function in C++?

A virtual function is a base-class member function that derived classes can override. When you call it through a base-class pointer or reference, C++ selects the implementation at runtime based on the object's actual type.

What is a cpp compiler?

A C++ compiler translates C++ source code into executable code or another form a computer can run. Common C++ compilers include GCC, Clang, and Microsoft Visual C++ (MSVC).

How to write "I love you" in C++?

Use `std::cout` to print the phrase in C++: ```cpp #include <iostream> int main() { std::cout << "I love you"; return 0; } ```

Is C++ very difficult?

C++ can be challenging because it has many features, and topics like pointers, memory management, and templates take practice. Beginners can learn it gradually by starting with basic syntax and small programs, then moving on to more advanced concepts.

What does return {} do in C++?

`return {};` returns a value-initialized result of the function's return type. For a standard container such as `std::vector<int>`, it returns an empty container; the exact effect depends on the return type.

Where can I download a free C++ compiler?

Free C++ compilers include GCC and Clang, available from their official websites, and MSVC, available through Microsoft's free Visual Studio Community edition. You can also use an online C++ compiler such as Compiler Explorer or OnlineGDB without installing one.

Read next

  1. C++ virtual functions: override, pure virtual and the trapsLanguage · Miriam Castellanos · written for C++11
  2. C++ vs C: what differs, what breaks, which to chooseCareers · Tobias Mwangi · written for C++23
  3. Java vs C++: what differs in the code, and which to chooseCareers · Tobias Mwangi · written for C++23