Legacy C++ › 3. Classes and Object-Oriented Programming
Virtual Functions and Polymorphism
Dynamic dispatch, vtables, virtual destructors and slicing.
intermediate #virtual#polymorphism#vtable#virtual-destructor#slicing#dynamic-dispatch
Explanation
A function declared virtual is resolved at run time by the object’s actual type (dynamic dispatch), not by the pointer or reference type. Typical implementations give each polymorphic class a hidden table of function pointers (the vtable) and each object a pointer to it, which is why polymorphic objects are slightly larger.
Rules:
- Overriding needs the same name, parameter types and constness. A mismatch silently creates a new function.
- Once virtual in a base, the function is virtual in all derived classes (the keyword is optional there).
- A base class meant for polymorphic use needs a virtual destructor.
- Dispatch happens only through pointers/references, not for objects passed by value.
Example
#include <iostream>
#include <vector>
class Shape {
public:
virtual ~Shape() {}
virtual double area() const = 0; // see Abstract Classes
virtual const char* name() const { return "shape"; }
};
class Circle : public Shape {
double r_;
public:
explicit Circle(double r) : r_(r) {}
double area() const { return 3.14159265 * r_ * r_; }
const char* name() const { return "circle"; }
};
class Square : public Shape {
double s_;
public:
explicit Square(double s) : s_(s) {}
double area() const { return s_ * s_; }
const char* name() const { return "square"; }
};
int main() {
std::vector<Shape*> shapes;
shapes.push_back(new Circle(1.0));
shapes.push_back(new Square(2.0));
for (std::size_t i = 0; i < shapes.size(); ++i)
std::cout << shapes[i]->name() << ": " << shapes[i]->area() << "\n";
for (std::size_t i = 0; i < shapes.size(); ++i)
delete shapes[i]; // safe thanks to the virtual destructor
return 0;
}
Common pitfalls
- Non-virtual destructor with
delete basePtris undefined behavior and leaks the derived part. - Slicing:
std::vector<Shape>or passingShapeby value copies only the base subobject. Store pointers (or smart pointers) or pass by reference. - Overriding with a different signature (
area()vsarea() const) hides rather than overrides. C++11’soverridecatches this. - Calling virtual functions in constructors/destructors does not dispatch to the derived class.
- Virtual calls cannot be inlined across the pointer, a small cost in hot loops.
Legacy vs modern
C++11 adds override, final, and smart pointers: std::vector<std::unique_ptr<Shape>> removes the manual delete. See enum class, override and final.
Exercises
1. What is printed by Shape* s = new Circle(1); std::cout << s->name(); if name is not virtual?
shape: the call binds statically to the pointer’s type.