Virtual functions are used in game design to let a shared base type—such as Entity, GameObject, or State—define a common interface while each concrete subtype supplies its own behavior, so engine code can call update(), render(), or collide() once and have the correct version run for each object. The qualification that makes this accurate is that virtual functions are a tool for runtime polymorphism within a single program, not a universal design requirement; they shine when you have a stable interface, a bounded set of implementations, and per-object behavior that varies by type. When those conditions fail—when the type set changes constantly, when behavior is data rather than code, or when per-call overhead is unacceptable—other patterns such as component systems, data tables, or function pointers often serve better. This article explains how virtual functions are actually applied in game code, why the pattern works, and where experienced designers deliberately avoid it.
The mechanics behind the pattern
A virtual function is a member function declared in a base class that a derived class can override. When you call it through a base-class pointer or reference, the language dispatches to the override that matches the object's actual dynamic type, not the type of the pointer. In C++, that dispatch normally goes through a per-object virtual table pointer pointing at a per-class table of function addresses; in C# and Java, similar mechanisms (interface/virtual dispatch, vtables or interface maps) apply. The important consequence for game code is that the caller does not need to know, or be updated for, the concrete type.
tickAll is written once. New enemy types plug in without touching the loop. That is the core value proposition, and it is why virtual functions appear in nearly every engine's entity, state, and resource abstractions.
The idiomatic uses in game code
Virtual functions are not one pattern; they show up in several well-established roles.
Entity and actor hierarchies. A base Entity or Actor declares update, render, onCollision, and serialize as virtual. Concrete classes—player, projectile, pickup, destructible—override what differs. Gameplay systems that iterate all entities then remain type-agnostic. The cost is that behavior is tied to class definitions, so every new enemy is a recompile.
State machines. A GameState base class with virtual enter, update, exit, and handleInput lets a game switch between menu, playing, paused, and game-over states without a giant conditional. Each state owns its transition rules. This is one of the cleanest uses because the state set is small and changes rarely.
Game loop and plugin seams. Engine-level virtuals let a project override file loading, input handling, or rendering backends without modifying the engine. The virtual call is a controlled extension point. The same idea underlies scripting bridges that expose a virtual onTick to embedded scripts.
Resource loaders. An Asset base with virtual load and unload, and subclasses for textures, meshes, and audio, keeps the resource manager generic.
Damage, effect, and behavior hooks. A DamageEffect base with a virtual apply(Target&) allows stacking burn, bleed, and stun as small derived classes. This is a reasonable use when the effect set is bounded and designers add them in code.
Why it works, and the design reasoning
The pattern rests on the substitution principle: code written against the base type must remain correct for every override. In a game, that means tickAll should not need to know whether the entity is a turret—only that it can update. Virtual functions enforce the interface while permitting the implementation to vary. That separation is what lets a team of programmers work on distinct enemy types in isolation and lets designers reason about the game loop as a black box.
The second reason is centralization of the invariant. The loop that advances time, the collision pipeline that calls onHit, and the save system that calls serialize each exist once. If instead every type had its own branch in a switch statement, that branching would be repeated in every system that touches entities, and it would drift. Virtual dispatch replaces "asked what type are you, then act" with "act." That inversion is the real design gain, and it matters more than any micro-performance consideration.
The distinctions that matter in practice
Several qualifications separate competent use from cargo-cult use.
Virtual functions are for open behavior, not open data. A hierarchy handles "what does this entity do differently?" badly when the answer is a table of numbers—health, speed, damage—because that is data, not behavior, and belongs in configuration. Use virtuals for logic, data tables for tuning.
The type set should be closed and known. The classic weakness of deep inheritance is the "fragile base class" and combinatorial explosion: fire flyer, ice flyer, fire walker, ice walker. If you find yourself multiplying subclasses for orthogonal traits (movement × element × AI), virtual inheritance is the wrong axis. Entity-component systems exist precisely because composition beats classification when attributes combine. Virtual functions assume a stable taxonomy; the games that broke them did so by making every new combination a class.
Construction and destruction need virtual destructors. A base-class pointer deleting a derived object without a virtual destructor is undefined behavior in C++. Every polymorphic base in a game resource manager or entity factory should declare virtual ~Base() = default;. This is the single most common real bug in hierarchy-based game code.
Never call virtual functions from constructors or destructors expecting overrides. During base construction, the dynamic type is the base, so the base version runs—the derived override does not. Game code that puts initialization into a constructor expecting polymorphic hook-in gets silent wrong behavior. Use a separate init() or factory function instead.
Dispatch has a cost, but usually not the one people fear. A virtual call is an indirect call, thwarting inlining and often causing a cache miss via the vtable pointer. For tens of thousands of per-frame calls this is measurable; for hundreds it is noise next to rendering and physics. Modern engines often mitigate determinism or cache concerns by grouping entities by type (structure-of-arrays) or by using function pointers stored in components, which is a data-oriented version of the same idea.
Virtual functions can hide expensive dependencies. Because the caller cannot see the override, a virtual call can secretly allocate, lock, load from disk, or block. In a hot loop, that is dangerous. Good game code documents which virtuals must be cheap and treats anything expensive (loading, pathfinding) as something to defer or route through a system, not bury inside update.
Composition is often the better default in modern engines. Unity's component model, Unreal's actor-component split, and ECS architectures all replace "override in a subclass" with "attach behavior." Virtual functions survive inside those systems for the stable seams—Component::update, State::tick—rather than as the primary mechanism for every entity. The mature position is not "virtuals versus ECS" but "virtuals for the framework's extension points, composition for object content."
A concrete comparison
| Concern | Virtual-function hierarchy | Component/ECS |
|---|---|---|
| Add a new entity type | New subclass, recompile | New component combo, data-driven |
| Orthogonal traits (fire + fly + AI) | Class explosion risk | Natural combination |
| Shared loop code | Written once against base | Written once against component list |
| Per-object tuning values | Code or config alongside class | Config/data |
| Best fit | States, resources, engine seams, bounded actor families | Large varying populations |
The table clarifies why both coexist: the hierarchy's strength is a stable, small interface; the component model's strength is combinatorial variation. A state machine full of virtuals is idiomatic; ten thousand entities each with unique class trees is usually a warning sign.
Common confusions, corrected
A few points trip people up. Overloading and overriding are different: a derived function with the same name but a different parameter list hides the base function rather than overriding it, so override (C++) or the virtual/override keywords elsewhere should be used explicitly to catch mistakes. Interface-only bases, where every function is pure virtual, are fine but force every subtype to implement all of them—sometimes the base should provide sensible defaults so subclasses override only what changes. And polymorphism is not unique to virtual functions: function pointers, std::function, delegates, and scripting hooks achieve dispatch too, at different trade-offs of type safety and flexibility. Virtual functions are simply the statically typed, compiler-checked default.
The design question to ask is not "can I use a virtual function here?" but "is this behavior that varies by a type the framework already knows about, and will the set of types stay small?" If yes, a virtual function is usually the clearest, safest expression. If behavior varies per instance, comes from data, or multiplies along independent axes, reach for composition.
Practical guidance
Start with virtuals at the framework's seams: the game state, the entity base, the resource loader. Keep the interface small and give it sane defaults so new types override only what differs. Declare virtual destructors. Avoid deep trees; one or two levels is healthy, and beyond that ask whether components would serve. Keep overrides cheap in per-frame paths. Profile before optimizing dispatch away. And do not fight the engine—if you are in Unity or Unreal, their component and behavior models already encode these trade-offs, and virtual functions are best used within them rather than to rebuild them. Used this way, virtual functions are not an academic curiosity but a precise instrument for making the game loop ignorant of how many kinds of things it is driving.