┌──────────────────────┬───────────────────────────────┬───────────────────────────────┐
│ Feature │ Static / Compile-Time │ Dynamic / Runtime │
├──────────────────────┼───────────────────────────────┼───────────────────────────────┤
│ Mechanism │ Overloading & Templates │ Virtual Functions & VTables │
│ Dispatch Timing │ Compiler resolves at compile │ CPU resolves at runtime │
│ Performance Overhead │ Zero runtime cost (Inlineable)│ VTable pointer lookup indirection│
│ Memory Overhead │ Slight code bloat (templates) │ 8-byte VPTR per object + VTable│
│ Flexibility │ Strict type checking at build │ Dynamic plug-and-play plugins │
└──────────────────────┴───────────────────────────────┴───────────────────────────────┘Polymorphism in C++: Compile-Time and Runtime Behavior
Direct Answer & Core Concept
Detailed Explanation & Mechanics
1. Comparison Matrix:
2. How Runtime Dispatch Works:
Each polymorphic class has a Virtual Method Table (vtable) containing function pointers. Each object stores a virtual table pointer (vptr).
Runnable Code Example: Polymorphism in C++
C++20 / C++23#include <iostream>
#include <vector>
#include <memory>
// 1. Compile-time Polymorphism (Function Overload)
void render(int score) { std::cout << "[Static] Integer score: " << score << "\n"; }
void render(double health) { std::cout << "[Static] Float health: " << health << "%\n"; }
// 2. Runtime Polymorphism (Virtual Hierarchy)
class Shape {
public:
virtual ~Shape() = default;
virtual void draw() const = 0; // Dynamic dispatch target
};
class Circle : public Shape {
public:
void draw() const override { std::cout << "[Dynamic] Drawing Circle (o)\n"; }
};
class Square : public Shape {
public:
void draw() const override { std::cout << "[Dynamic] Drawing Square [ ]\n"; }
};
int main() {
// Compile-time resolution
render(100);
render(98.5);
// Runtime dynamic dispatch
std::vector<std::unique_ptr<Shape>> canvas;
canvas.push_back(std::make_unique<Circle>());
canvas.push_back(std::make_unique<Square>());
for (const auto& s : canvas) {
s->draw(); // Resolved via vptr -> vtable at runtime
}
return 0;
}Common C++ Technical Interview Questions & Answers
Interview PrepQ: What is a vtable and where does it reside in memory?
Q: What is the memory overhead of virtual functions in an object?
Key Takeaways, Modern Best Practices & Idioms
C++ Best Practices & Production Rules
• Use runtime polymorphism when collections of heterogeneous types must be managed uniformly.
• Always mark overriding methods with the
override keyword to catch signature mismatches at compile time.