Introduction & Syntax
Polymorphism and Virtual Functions · Study material
Polymorphism in C++ – "many forms" – lets one piece of code work with objects of many different types. With virtual functions, a call through a base-class pointer or reference runs the version that belongs to the object's actual type, decided at run time. That single idea powers plug-in architectures, GUI frameworks, game entities, payment gateways and every design pattern built on interfaces. C++ also offers compile-time polymorphism through overloading, templates, CRTP and std::variant. "How do virtual functions work?", "what is a vtable?" and "why does a base class need a virtual destructor?" are among the most asked C++ interview questions. This page answers them all with programs you can run, followed by 60 practice questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – verified on a real C++ compiler.
On this page
- Compile-time vs run-time polymorphism
- Virtual functions, dynamic dispatch, override and final
- How it works: vtables and vptrs, and the cost
- Virtual destructors, covariant return types, the classic pitfalls
- NVI, dynamic_cast/typeid, and static alternatives (templates, CRTP, std::variant)
Two kinds of polymorphism
| Compile-time (static) | Run-time (dynamic) | |
|---|---|---|
| Decided | by the compiler | while the program runs |
| Mechanisms | function and operator overloading, templates, CRTP, std::variant + std::visit | virtual functions called through base pointers/references |
| Cost | none at run time (can be inlined) | one indirect call through the vtable |
| Set of types | known when compiling | open – new derived classes can be added later |
Virtual functions and dynamic dispatch
Declaring a member function virtual in a base class means: when it is called through a pointer or reference to the base, run the most-derived override for the object actually there. Non-virtual functions are chosen from the static type of the expression. A function that overrides a virtual function is virtual too, with or without the keyword.
#include <iostream>
#include <memory>
#include <vector>
class Shape {
public:
virtual double area() const { return 0; } // virtual: resolved at run time
const char* kind() const { return "shape"; } // non-virtual: resolved at compile time
virtual ~Shape() = default;
};
class Circle : public Shape {
double r_;
public:
explicit Circle(double r) : r_(r) {}
double area() const override { return 3.14159 * r_ * r_; }
const char* kind() const { return "circle"; } // hides, does not override
};
class Square : public Shape {
double s_;
public:
explicit Square(double s) : s_(s) {}
double area() const override { return s_ * s_; }
};
int main() {
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(1));
shapes.push_back(std::make_unique<Square>(2));
for (const auto& s : shapes)
std::cout << s->kind() << ' ' << s->area() << '\n'; // area: real type; kind: pointer type
return 0;
}
shape 3.14159 shape 4
Dynamic dispatch happens only through pointers and references. Calling on an object by name, or on a copy passed by value (which is sliced), uses its static type.
#include <iostream>
struct Animal {
virtual const char* sound() const { return "..."; }
virtual ~Animal() = default;
};
struct Dog : Animal {
const char* sound() const override { return "Woof"; }
};
void by_ref(const Animal& a) { std::cout << a.sound() << ' '; } // dynamic dispatch
void by_ptr(const Animal* a) { std::cout << a->sound() << ' '; } // dynamic dispatch
void by_val(Animal a) { std::cout << a.sound() << ' '; } // sliced copy: always Animal
int main() {
Dog d;
by_ref(d);
by_ptr(&d);
by_val(d);
std::cout << '\n';
return 0;
}
Woof Woof ...
override and final
Write override on every overriding function: the compiler then checks that it really matches a base virtual function – a missing const or a different parameter type becomes a compile error instead of a silent new function. final on a virtual function stops further overriding; on a class it stops derivation. Inside an override, Base::f() calls the base implementation.
#include <iostream>
class Notifier {
public:
virtual void send(const char* msg) const { std::cout << "generic: " << msg << '\n'; }
virtual int priority() const { return 1; }
virtual ~Notifier() = default;
};
class Sms : public Notifier {
public:
void send(const char* msg) const override { std::cout << "SMS: " << msg << '\n'; }
int priority() const final { return 5; } // no further overriding allowed
// void send(std::string msg) const override; error: does not override anything
};
class UrgentSms final : public Sms { // no further derivation allowed
public:
void send(const char* msg) const override { Sms::send(msg); std::cout << " (also called)\n"; }
};
int main() {
UrgentSms u;
const Notifier& n = u;
n.send("server down");
std::cout << n.priority() << '\n';
return 0;
}
SMS: server down (also called) 5
How virtual functions work: vtables and vptrs
Compilers implement dynamic dispatch with a vtable per class – an array of pointers to that class's implementations of its virtual functions – and a hidden vptr in every object that points to its class's vtable. A virtual call loads the vptr, looks up the slot and calls through it. So each polymorphic object grows by one pointer (whatever the number of virtual functions), and each call costs one indirection and usually prevents inlining.
#include <iostream>
struct Plain { int x; void f() {} };
struct Virtual { int x; virtual void f() {} virtual void g() {} virtual ~Virtual() = default; };
struct Derived : Virtual { void f() override {} };
int main() {
// One hidden pointer (vptr) per object, whatever the number of virtual functions
std::cout << sizeof(Plain) << ' ' << sizeof(Virtual) << ' ' << sizeof(Derived) << '\n';
return 0;
}
4 16 16
Virtual destructors
If an object of a derived class is deleted through a pointer to its base, and the base destructor is not virtual, the behaviour is undefined – typically the derived destructor never runs and its resources leak. Rule: every class meant to be used polymorphically needs a public virtual destructor (or a protected non-virtual one, if deletion through the base must be forbidden).
#include <iostream>
#include <memory>
struct Resource {
virtual ~Resource() { std::cout << "~Resource "; }
};
struct File : Resource {
~File() override { std::cout << "~File(close handle) "; }
};
int main() {
std::unique_ptr<Resource> r = std::make_unique<File>();
r.reset(); // deletes through Resource*: ~File runs first because ~Resource is virtual
std::cout << '\n';
return 0;
}
~File(close handle) ~Resource
Pitfalls: default arguments and calls from constructors
Two rules surprise many programmers. Default arguments are taken from the static type of the call, even though the function body comes from the dynamic type – so never give overrides different defaults. And during a base class's constructor or destructor, the derived part does not exist, so virtual calls go to the base version.
#include <iostream>
struct Base {
Base() { hello(); } // during construction: Base::hello
virtual void hello() const { std::cout << "Base::hello\n"; }
virtual void greet(const char* who = "base default") const { std::cout << "Base greets " << who << '\n'; }
virtual ~Base() = default;
};
struct Derived : Base {
Derived() { hello(); }
void hello() const override { std::cout << "Derived::hello\n"; }
void greet(const char* who = "derived default") const override { std::cout << "Derived greets " << who << '\n'; }
};
int main() {
Derived d;
const Base& b = d;
b.greet(); // function chosen at run time, DEFAULT ARGUMENT chosen at compile time!
d.greet();
return 0;
}
Base::hello Derived::hello Derived greets base default Derived greets derived default
Covariant return types
An override may return a pointer or reference to a class derived from the one the base function returns. This is how a "virtual copy constructor" – clone() – returns the precise type when called on a derived object.
#include <iostream>
#include <memory>
struct Shape {
virtual Shape* clone() const = 0;
virtual const char* name() const = 0;
virtual ~Shape() = default;
};
struct Circle : Shape {
double r = 1;
Circle* clone() const override { return new Circle(*this); } // covariant: Circle* instead of Shape*
const char* name() const override { return "circle"; }
};
int main() {
Circle c;
c.r = 7;
std::unique_ptr<Circle> c2(c.clone()); // no cast needed: clone() returns Circle*
const Shape& s = c;
std::unique_ptr<Shape> s2(s.clone()); // through the base: still copies a Circle
std::cout << c2->r << ' ' << s2->name() << '\n';
return 0;
}
7 circle
Overloading, overriding and hiding
| Overloading | Overriding | Hiding | |
|---|---|---|---|
| Where | same scope | derived class | derived class |
| Signature | different parameters | same signature, base function virtual | same name, base function non-virtual or different signature |
| Resolved | compile time | run time | compile time (static type) |
Polymorphism without virtual functions
When the set of types is known in advance, compile-time techniques avoid the vtable entirely: function templates, the Curiously Recurring Template Pattern (a base class template that calls the derived class through static_cast), and std::variant with std::visit for a closed set of alternatives that need no common base class.
#include <iostream>
#include <string>
#include <variant>
#include <vector>
// 1. Templates: the right function is chosen at compile time
template <typename T>
T twice(T x) { return x + x; }
// 2. CRTP: "virtual-like" calls with no vtable
template <typename Derived>
struct Greeter {
void greet() const { std::cout << "Hello, " << static_cast<const Derived*>(this)->name() << "! "; }
};
struct Asha : Greeter<Asha> { std::string name() const { return "Asha"; } };
struct Ravi : Greeter<Ravi> { std::string name() const { return "Ravi"; } };
// 3. std::variant + std::visit: a closed set of types, no inheritance at all
struct Circle { double r; };
struct Rect { double w, h; };
using Shape = std::variant<Circle, Rect>;
struct Area {
double operator()(const Circle& c) const { return 3.0 * c.r * c.r; }
double operator()(const Rect& r) const { return r.w * r.h; }
};
int main() {
std::cout << twice(21) << ' ' << twice(std::string("ab")) << '\n';
Asha{}.greet();
Ravi{}.greet();
std::cout << '\n';
std::vector<Shape> shapes{Circle{2}, Rect{3, 4}};
double total = 0;
for (const auto& s : shapes) total += std::visit(Area{}, s);
std::cout << total << '\n';
return 0;
}
42 abab Hello, Asha! Hello, Ravi! 24
Common mistakes
- Forgetting virtual in the base class – derived versions merely hide it.
- Signature mismatches (missing const, different parameter type) – use override.
- No virtual destructor in a polymorphic base.
- Passing polymorphic objects by value – slicing.
- Different default arguments in overrides.
- Calling virtual functions from constructors expecting derived behaviour.
- Using dynamic_cast chains instead of adding a virtual function.
Key points to remember
- virtual + call through pointer/reference = the real type's function runs.
- Mark every override with override; use final to stop overriding.
- One vptr per object, one vtable per class.
- Polymorphic bases need virtual destructors.
- Default arguments bind statically; virtual calls in constructors are not dispatched to derived classes.
- Templates, CRTP and std::variant give polymorphism without vtables.
Frequently asked questions
What is the difference between a virtual and a pure virtual function?
A virtual function has an implementation that derived classes may override. A pure virtual function (= 0) need not have one and makes its class abstract; derived classes must override it to be instantiable. Abstract classes are covered in Abstract Classes and Interfaces.
Are virtual functions slow?
A virtual call costs one extra indirection and usually prevents inlining – negligible in most code, noticeable only in very hot inner loops, where templates or std::variant can help.
Can static or template member functions be virtual?
No. Static functions have no object to dispatch on, and member function templates cannot be virtual because the vtable would need an entry for every possible instantiation.
Where can I learn more?
Read C++ Inheritance and Polymorphism and Object-Oriented Programming in C++, then practise with the exercises below.