Virtual function

Also known as: virtual method

On this page 7

A virtual function, also called a virtual method, is a member function declared in a base class whose call is resolved at run time according to the actual type of the object, not the static type of the reference or pointer used to make the call. In object-oriented programming, it is the mechanism that turns inheritance into runtime polymorphism: code written against a base class automatically invokes the behavior supplied by whichever derived class the object really belongs to.

The term comes from C++, where the virtual keyword makes this behavior explicit, but the concept exists in nearly every class-based language. In Java and Python, ordinary instance methods are virtual by default, while C++ and C# require the programmer to opt in, which reflects a deliberate trade-off between flexibility and performance.

How a virtual function call is dispatched

A virtual function call is dispatched by looking up the correct implementation through data attached to the object itself. Most C++ compilers implement this with a virtual method table, usually called the vtable: one table per class, containing pointers to the implementations of every virtual function that class exposes.

Each object of a polymorphic class carries a hidden vtable pointer (often named vptr) that the constructor sets to the table of the object’s class. A call such as shape->area() compiles into three steps: load the vptr from the object, load the function pointer stored at the fixed slot for area, and perform an indirect call through that pointer. Because the slot index is known at compile time, the lookup has constant cost regardless of how deep the hierarchy is.

The table below summarizes the components that take part in this mechanism and the role each one plays.

ComponentWhere it livesRole in the call
Virtual method tableStatic data, one per classMaps each virtual slot to an implementation
Vtable pointerInside every objectIdentifies the dynamic type at run time
Slot indexFixed by the compilerSelects the function within the table
OverrideDerived class codeReplaces the base entry in the derived table
ThunkGenerated codeAdjusts this under multiple inheritance
Components of vtable-based dispatch

Languages with virtual-by-default methods use comparable structures. The Java Virtual Machine resolves invokevirtual through per-class method tables, and CPython looks up attributes through the type’s method resolution order, which is slower but follows the same principle of late binding.

Variants of virtual functions

Virtual functions come in several variants that differ in whether a base implementation exists and whether further overriding is allowed. The most important distinction is between an ordinary virtual function, which provides a default implementation, and a pure virtual function, which declares only a contract.

In C++, a pure virtual function is written with the = 0 specifier, and any class containing one becomes an abstract class that cannot be instantiated. This is the C++ equivalent of an abstract method in Java or C#, and a class consisting only of pure virtual functions behaves much like an interface.

KindDeclaration formEffect on the class
Ordinary virtualvirtual void draw();Derived classes may override; base version is used otherwise
Pure virtualvirtual void draw() = 0;Class becomes abstract; derived classes must implement it
Overridevoid draw() override;Compiler verifies a matching base virtual exists
Final overridevoid draw() final;No further derived class may override it
Virtual destructorvirtual ~Shape();Deleting through a base pointer runs the derived destructor
Kinds of virtual functions in C++ and their effect

The override specifier, introduced in C++11, is a safety feature rather than a dispatch feature. It turns a silent mistake, such as a mismatched parameter type that accidentally declares a new function instead of overriding, into a compile-time error.

A virtual function is one specific way of achieving dynamic dispatch, and it is often confused with neighboring concepts. Method overriding is the act of supplying a new implementation in a derived class; the virtual declaration is what makes that override visible through a base reference. Method overloading, by contrast, is resolved entirely at compile time from argument types.

The following comparison clarifies when binding happens and what drives the choice of implementation in each case.

TechniqueWhen the target is chosenWhat decides the target
Virtual functionRun timeDynamic type of the receiving object
Non-virtual member functionCompile timeStatic type of the expression
Method overloadingCompile timeNumber and types of arguments
Templates and genericsCompile timeType parameters at instantiation
Multiple dispatchRun timeDynamic types of several arguments
Binding behavior of related techniques

Calling a non-virtual function through a base pointer in C++ executes the base version even when the object is derived, a behavior known as name hiding. Developers moving from Java frequently expect overriding semantics in this situation and are surprised by the result.

Performance cost and design trade-offs

The cost of a virtual function call is small in isolation but significant in tight loops. The indirect call itself typically adds only a few cycles on modern processors, provided the branch predictor guesses the target correctly. The larger cost is usually the lost inlining opportunity: the compiler cannot inline a call whose target is unknown, which blocks further optimizations such as constant propagation and vectorization.

Each polymorphic object also grows by the size of one pointer, typically 8 bytes on 64-bit platforms, which matters for millions of small objects. Compilers mitigate some of these costs through devirtualization: when analysis proves the dynamic type, for example because a class is marked final, the call is converted to a direct one.

The decision table below summarizes common situations and the usual recommendation.

SituationRecommendationReason
Class is designed as a polymorphic baseDeclare a virtual destructorPrevents incomplete destruction
Behavior must vary by subclassMake the function virtualEnables runtime substitution
Hot loop over millions of objectsConsider static dispatchAvoids indirect calls and lost inlining
Class is not meant to be extendedMark it finalDocuments intent and enables devirtualization
Set of types is closed and smallConsider a variant typeAllows exhaustive compile-time checking
When to declare a function virtual

Common mistakes with virtual functions

Most defects involving virtual functions arise from subtle language rules rather than from the dispatch mechanism itself. Experienced C++ reviewers check the following points routinely.

  • Missing virtual destructor: deleting a derived object through a base pointer without one is undefined behavior and commonly leaks resources.
  • Calling virtual functions in constructors: during base construction the object has the base dynamic type, so the derived override is not called.
  • Object slicing: copying a derived object into a base-class value discards the derived part, and later calls dispatch to the base version.
  • Signature drift: a changed parameter or a missing const creates a new function instead of an override; the override specifier catches this.
  • Default arguments: they are bound statically, so a derived override may run with the base class default value.

Stripped to the essentials

A virtual function lets a program ask an object to do something without knowing exactly what kind of object it is. Think of a universal remote with a single play button. The button is the same, but a DVD player, a streaming box and a speaker each respond in their own way.

In code, a general category such as a shape defines the button, and each specific shape decides what pressing it means. The key idea is that the object itself chooses the right behavior at the moment the program runs, so new kinds of objects can be added without rewriting the code that uses them.

Where it is applied

A team building a desktop drawing application defines a base class Shape with a pure virtual function render(Canvas&) and a virtual destructor. Circles, rectangles, text boxes and imported vector paths each derive from it and implement their own rendering. The editor stores every element of a document in a single list of pointers to Shape and redraws the page by calling render on each one.

When the team later adds a new element type for embedded charts, only the new class is written; the drawing loop, undo history and export code remain unchanged. Profiling a document with about 50,000 elements shows that virtual dispatch accounts for well under one percent of frame time, so the team keeps the design and marks leaf classes final to let the compiler devirtualize where it can. The outcome is extensibility without measurable performance loss.