At the end of Inheritance we hit a wall. We had a Dog object, referred to it through an Animal&, called speak(), and got the generic Animal sound instead of "Woof!". The compiler looked at the type of the reference, not the type of the object.
That is a serious limitation. Imagine a drawing app that keeps a list of shapes. We want to write shape.draw() once and have circles draw circles and squares draw squares, without a long if/else chain that must be edited every time a new shape is added. That ability, one interface with many behaviours chosen by the actual object, is polymorphism, and in C++ it is powered by virtual functions.
In this chapter you will learn the two kinds of polymorphism, how virtual, override and final work, why base classes need virtual destructors, how the vtable mechanism works under the hood, and the classic traps: object slicing, virtual calls in constructors and default arguments. These topics are asked in almost every C++ interview.
What Is Polymorphism?
Polymorphism (Greek: "many forms") is the ability of the same function call or operator to behave differently depending on the type of the object or arguments it is used with.
C++ has two kinds, distinguished by when the decision is made:
| Compile-time (static) polymorphism | Run-time (dynamic) polymorphism | |
|---|---|---|
| Decided | By the compiler | While the program runs |
| Also called | Static binding, early binding | Dynamic binding, late binding, dynamic dispatch |
| Mechanisms | Function overloading, operator overloading, templates | Virtual functions, called through a pointer or reference to a base class |
| Based on | Static types of the arguments | Dynamic type of the object |
| Cost | No run-time cost | A small indirect-call cost per call |
| Covered in | Function Overloading, Operator Overloading, later Templates | This chapter |
Two more terms are essential:
- The static type of an expression is the type the compiler sees in the source code. For
Animal& ref = d;, the static type ofrefisAnimal. - The dynamic type is the type of the actual object it refers to at run time, here
Dog.
Non-virtual calls are chosen by the static type. Virtual calls are chosen by the dynamic type.
Virtual Functions
A virtual function is a non-static member function declared with the keyword
virtualin a base class. When it is called through a pointer or reference to the base class, the version belonging to the dynamic type of the object is executed.
A derived-class function with the same name, same parameter types, same const/reference qualifiers (and a compatible return type) overrides the base version. It is automatically virtual too, with or without the keyword.
#include <iostream>
class Shape {
public:
virtual void draw() const { // virtual!
std::cout << "Drawing a generic shape\n";
}
virtual ~Shape() = default; // explained later
};
class Circle : public Shape {
public:
void draw() const override { std::cout << "Drawing a circle\n"; }
};
class Square : public Shape {
public:
void draw() const override { std::cout << "Drawing a square\n"; }
};
void render(const Shape& s) { // works for ANY shape, even future ones
s.draw(); // decided at run time
}
int main() {
Circle c;
Square sq;
Shape plain;
render(c);
render(sq);
render(plain);
const Shape* shapes[] = { &sq, &c, &sq };
for (const Shape* p : shapes)
p->draw();
}
Output:
Drawing a circle
Drawing a square
Drawing a generic shape
Drawing a square
Drawing a circle
Drawing a square
The function render() was compiled knowing only about Shape. Yet it drew circles and squares correctly, and it will draw a Triangle too if someone adds one next year, without changing or even recompiling render(). That is the real power of run-time polymorphism: code that depends on an interface, not on a list of concrete types. (This is the "open for extension, closed for modification" idea from good software design.)
Three conditions for dynamic dispatch
- The function is virtual in the base class.
- The derived class overrides it with a matching signature.
- It is called through a pointer or reference to the base class (calling directly on an object uses that object's own type, which is known anyway).
Also, the inheritance must be public for outside code to convert Circle* to Shape*, as we saw in Inheritance.
The override Specifier (C++11)
Overriding requires an exact match. Miss a const or use int instead of long, and you silently create a brand-new function instead of an override:
#include <iostream>
class Logger {
public:
virtual void log(const char* msg) const {
std::cout << "[LOG] " << msg << '\n';
}
virtual ~Logger() = default;
};
class FileLogger : public Logger {
public:
// Typo: forgot 'const', so this does NOT override Logger::log
void log(const char* msg) {
std::cout << "[FILE] " << msg << '\n';
}
};
int main() {
FileLogger f;
const Logger& lg = f;
lg.log("hello"); // which version runs?
}
Output:
[LOG] hello
The FileLogger version never ran, because log(const char*) (non-const) is a different function from log(const char*) const. It merely hides the base function, exactly like the name hiding we saw in Inheritance. GCC 15 with -Wall does warn about this (-Woverloaded-virtual, enabled by -Wall since GCC 13):
warning: ‘virtual void Logger::log(const char*) const’ was hidden [-Woverloaded-virtual=]
note: by ‘void FileLogger::log(const char*)’
But a warning is easy to miss. The reliable fix is to write override on every overriding function. It tells the compiler "this must override something", turning the mistake into a hard error:
class Logger {
public:
virtual void log(const char* msg) const;
virtual ~Logger() = default;
};
class FileLogger : public Logger {
public:
void log(const char* msg) override; // missing const
};
int main() {}
error: ‘void FileLogger::log(const char*)’ marked ‘override’, but does not override
Good modern style: write virtual only on the first declaration in the base class, and override (without virtual) on every override.
The final Specifier (C++11)
In Inheritance we used final on a class. On a virtual function, final means "this is the last override; classes further down may not override it again":
class Base {
public:
virtual void step() {}
virtual ~Base() = default;
};
class Middle : public Base {
public:
void step() final {} // last override allowed
};
class Leaf : public Middle {
public:
void step() override {} // error
};
int main() {}
error: virtual function ‘virtual void Leaf::step()’ overriding final function
note: overridden function is ‘virtual void Middle::step()’
Besides documenting design intent, final can help performance: when the compiler knows a function cannot be overridden further, it can sometimes replace a virtual call with a direct call (devirtualization).
Note that override and final are not reserved keywords; they have special meaning only in these positions, so old code using them as variable names still compiles.
Virtual Destructors
This is the single most important rule in this chapter:
If objects of a derived class may be deleted through a pointer to the base class, the base class destructor must be virtual. Otherwise the behaviour is undefined.
Here is the bug:
#include <iostream>
class Base {
public:
Base() { std::cout << "Base()\n"; }
~Base() { std::cout << "~Base()\n"; } // NOT virtual
virtual void work() {}
};
class Derived : public Base {
int* data;
public:
Derived() : data(new int[100]) { std::cout << "Derived(): allocated\n"; }
~Derived() { delete[] data; std::cout << "~Derived(): freed\n"; }
};
int main() {
Base* p = new Derived;
delete p; // undefined behavior: ~Base is not virtual
}
GCC warns at compile time (-Wdelete-non-virtual-dtor, part of -Wall):
warning: deleting object of polymorphic class type ‘Base’ which has non-virtual destructor might cause undefined behavior
When we ran it anyway, this build printed:
Base()
Derived(): allocated
~Base()
~Derived() never ran, so the 400-byte array leaked. And that is just what happened on this run; formally the behaviour is undefined, so anything may happen. AddressSanitizer catches it immediately (compile with -fsanitize=address,undefined):
ERROR: AddressSanitizer: new-delete-type-mismatch
object passed to delete has wrong type:
size of the allocated type: 16 bytes;
size of the deallocated type: 8 bytes.
The fix is one word:
#include <iostream>
class Base {
public:
Base() { std::cout << "Base()\n"; }
virtual ~Base() { std::cout << "~Base()\n"; } // virtual destructor
virtual void work() {}
};
class Derived : public Base {
int* data;
public:
Derived() : data(new int[100]) { std::cout << "Derived(): allocated\n"; }
~Derived() override { delete[] data; std::cout << "~Derived(): freed\n"; }
};
int main() {
Base* p = new Derived;
delete p; // correct: ~Derived runs first, then ~Base
}
Output:
Base()
Derived(): allocated
~Derived(): freed
~Base()
Now delete p dispatches to ~Derived(), which runs and then automatically calls ~Base(), the normal destruction order from Inheritance. Once a base destructor is virtual, every derived destructor is virtual automatically (the override on ~Derived() is optional but allowed).
Practical rule: any class with at least one virtual function should have a public virtual destructor (often just virtual ~Base() = default;). Declaring a destructor this way suppresses the implicit move operations, so if the class also needs to be copied or moved, declare those explicitly too (the Rule of Five from Operator Overloading applies). Constructors, on the other hand, can never be virtual: when an object is being created, its exact type is already known.
How Virtual Functions Work: vtable and vptr
The C++ standard only describes what virtual calls do, not how. But essentially every compiler (GCC, Clang and MSVC) uses the same idea:
- For every class with virtual functions, the compiler builds one virtual table (vtable): an array of pointers to the correct function for that class. It is shared by all objects of the class.
- Each object of such a class gets a hidden pointer, the vptr, pointing to its class's vtable. The constructor sets it.
- A virtual call
p->draw()becomes: followpto the object, read its vptr, look up thedrawslot in the table, call that function.
Circle object vtable for Circle
+-------------+ +----------------------+
| vptr -----+-------→ | slot 0: Circle::draw |
| ...data | | slot 1: ~Circle |
+-------------+ +----------------------+
Square object vtable for Square
+-------------+ +----------------------+
| vptr -----+-------→ | slot 0: Square::draw |
| ...data | | slot 1: ~Square |
+-------------+ +----------------------+
shape->draw() ⇒ (*(shape->vptr)[0])(shape) same code, different table
(Slots follow the order in which the virtual functions were declared in Shape. The layout is simplified: the real Itanium C++ ABI used by GCC and Clang adds extra entries, such as two destructor slots and a pointer to the type information used by typeid.) You can see the hidden pointer in sizeof:
#include <iostream>
struct NoVirtual { int x; void f() {} };
struct WithVirtual { int x; virtual void f() {} };
struct MoreVirtual { int x; virtual void f() {} virtual void g() {} virtual void h() {} };
int main() {
std::cout << "sizeof(NoVirtual) = " << sizeof(NoVirtual) << '\n';
std::cout << "sizeof(WithVirtual) = " << sizeof(WithVirtual) << '\n';
std::cout << "sizeof(MoreVirtual) = " << sizeof(MoreVirtual) << '\n';
}
Output (64-bit Linux):
sizeof(NoVirtual) = 4
sizeof(WithVirtual) = 16
sizeof(MoreVirtual) = 16
Adding one virtual function grew the object from 4 to 16 bytes: an 8-byte vptr, the 4-byte int, and 4 bytes of padding for alignment. Adding more virtual functions did not grow the object, because they only add entries to the shared vtable. The cost of polymorphism is therefore:
- Space: one pointer per object, one table per class.
- Time: an indirect call, which usually cannot be inlined. For most programs this is negligible; in very hot loops it can matter.
Object Slicing
Polymorphism works through pointers and references. If you copy a derived object into a base object, only the base part is copied. The derived part is "sliced off", and the copy really is a base object, vptr and all:
#include <iostream>
#include <string>
class Animal {
public:
virtual std::string sound() const { return "..."; }
virtual ~Animal() = default;
};
class Cat : public Animal {
public:
std::string sound() const override { return "Meow"; }
};
void byValue(Animal a) { std::cout << "by value: " << a.sound() << '\n'; }
void byReference(const Animal& a) { std::cout << "by reference: " << a.sound() << '\n'; }
int main() {
Cat c;
byValue(c); // the Cat part is sliced off
byReference(c); // the real Cat is used
Animal copy = c; // slicing again: copy is a plain Animal
std::cout << "copy says: " << copy.sound() << '\n';
}
Output:
by value: ...
by reference: Meow
copy says: ...
Cat c Animal a (parameter by value)
+--------------------+ +--------------------+
| Animal part | copy | Animal part |
| vptr → Cat table | -----→ | vptr → Animal | ← constructor of Animal
+--------------------+ +--------------------+ sets Animal's vptr
| Cat-only members | ✗ (nowhere to put them)
+--------------------+
Rules to avoid slicing: pass polymorphic objects by reference (usually const&) or pointer, and store them in containers as pointers (later, smart pointers), not by value. Slicing also happens when you store a Cat in a std::vector<Animal>.
Virtual Calls in Constructors and Destructors
What happens if a base constructor calls a virtual function?
#include <iostream>
class Base {
public:
Base() {
std::cout << "In Base(): ";
hello(); // virtual call during construction
}
virtual void hello() const { std::cout << "Base::hello\n"; }
virtual ~Base() {
std::cout << "In ~Base(): ";
hello(); // and during destruction
}
};
class Derived : public Base {
public:
Derived() {
std::cout << "In Derived(): ";
hello();
}
void hello() const override { std::cout << "Derived::hello\n"; }
};
int main() {
Derived d;
std::cout << "In main: ";
d.hello();
}
Output:
In Base(): Base::hello
In Derived(): Derived::hello
In main: Derived::hello
In ~Base(): Base::hello
Inside Base() the call went to Base::hello, not Derived::hello. This is well-defined, deliberate behaviour: while the Base constructor runs, the Derived members have not been initialised yet, so calling a Derived function could read garbage. C++ therefore treats the object as a Base during the base constructor (the vptr points at Base's table), and again during the base destructor, when the Derived part has already been destroyed.
If the function called this way is pure virtual (covered in the next chapter), the behaviour is undefined. So: do not rely on virtual calls in constructors and destructors.
Default Arguments in Virtual Functions
A tricky interview favourite. Predict the output before reading it:
#include <iostream>
class Base {
public:
virtual void show(int n = 10) const { std::cout << "Base::show " << n << '\n'; }
virtual ~Base() = default;
};
class Derived : public Base {
public:
void show(int n = 20) const override { std::cout << "Derived::show " << n << '\n'; }
};
int main() {
Derived d;
const Base& b = d;
b.show(); // function from the dynamic type, default from the static type!
d.show();
}
Output:
Derived::show 10
Derived::show 20
The function body comes from the dynamic type (Derived::show), but the default argument comes from the static type (Base, so 10). Default arguments are filled in by the compiler at the call site, at compile time, using the declaration it can see. Rule: never redefine default arguments in an override; ideally avoid default arguments on virtual functions altogether.
Covariant Return Types
An override must normally have the same return type. One exception: if the base function returns a pointer or reference to a class B, the override may return a pointer or reference to a class derived from B. This is called a covariant return type, and it is mostly used for the "virtual copy constructor" (clone) idiom:
#include <iostream>
class Shape {
public:
virtual Shape* clone() const { return new Shape(*this); }
virtual const char* name() const { return "Shape"; }
virtual ~Shape() = default;
};
class Circle : public Shape {
public:
Circle* clone() const override { return new Circle(*this); } // covariant return
const char* name() const override { return "Circle"; }
};
int main() {
Circle c;
const Shape& s = c;
Shape* copy = s.clone(); // a new Circle, through a Shape&
std::cout << copy->name() << '\n';
Circle* direct = c.clone(); // no cast needed: returns Circle*
std::cout << direct->name() << '\n';
delete copy;
delete direct;
}
Output:
Circle
Circle
Since constructors cannot be virtual, clone() is how you copy an object when you only have a base reference to it. (Returning a raw owning pointer is kept here for simplicity; the Smart Pointers chapter shows the modern version.)
Downcasting: dynamic_cast and typeid
Going from a base pointer back to a derived pointer is called downcasting. It is not always valid (a Vehicle* may point to a Bike), so C++ provides a checked cast that uses the run-time type information (RTTI) stored alongside the vtable:
#include <iostream>
#include <typeinfo>
class Vehicle {
public:
virtual ~Vehicle() = default;
};
class Car : public Vehicle {
public:
void openSunroof() const { std::cout << "Sunroof opened\n"; }
};
class Bike : public Vehicle {};
void inspect(Vehicle* v) {
if (Car* car = dynamic_cast<Car*>(v)) { // nullptr if v is not a Car
car->openSunroof();
} else {
std::cout << "Not a car\n";
}
}
int main() {
Car c;
Bike b;
inspect(&c);
inspect(&b);
Vehicle& ref = b;
std::cout << std::boolalpha
<< (typeid(ref) == typeid(Bike)) << '\n' // dynamic type: Bike
<< (typeid(ref) == typeid(Vehicle)) << '\n';
}
Output:
Sunroof opened
Not a car
true
false
dynamic_cast<Car*>(v)returnsnullptrif*vis not aCar(or derived fromCar). The reference formdynamic_cast<Car&>(r)throwsstd::bad_castinstead.- Downcasting with
dynamic_castrequires the source type to be polymorphic (have at least one virtual function);Vehicle's virtual destructor is enough. typeidon a polymorphic object reports its dynamic type.static_castcan also downcast but performs no check; if the object is not really aCar, using the result is undefined behaviour.
If you find yourself writing many dynamic_casts, it usually means a virtual function is missing from the base class.
Putting It Together: Replacing if/else with Polymorphism
A typical design: a checkout that supports several payment methods. The = 0 below makes pay a pure virtual function, meaning every derived class must override it; the next chapter is dedicated to it.
#include <iostream>
class Payment {
public:
virtual void pay(double amount) const = 0; // must be overridden
virtual ~Payment() = default;
};
class UpiPayment : public Payment {
public:
void pay(double amount) const override { std::cout << "Paid Rs " << amount << " via UPI\n"; }
};
class CardPayment : public Payment {
public:
void pay(double amount) const override { std::cout << "Paid Rs " << amount << " by card\n"; }
};
class Checkout {
const Payment& method;
public:
explicit Checkout(const Payment& m) : method(m) {}
void complete(double total) const { method.pay(total); } // no if/else on type!
};
int main() {
UpiPayment upi;
CardPayment card;
Checkout(upi).complete(499);
Checkout(card).complete(1250.5);
}
Output:
Paid Rs 499 via UPI
Paid Rs 1250.5 by card
Checkout never asks "which kind of payment is this?". Adding a WalletPayment means writing one new class; Checkout stays untouched.
Overloading vs Overriding vs Hiding
| Overloading | Overriding | Hiding (redefining) | |
|---|---|---|---|
| Where | Same scope | Base and derived class | Base and derived class |
| Signature | Must differ in parameters | Must match exactly (covariant return allowed) | Same name; signature may or may not match |
virtual needed? | No | Yes, in the base | No (base function not virtual, or signature differs) |
| Resolved | Compile time | Run time (through pointer/reference) | Compile time, by static type |
| Polymorphism type | Static | Dynamic | None |
What Can and Cannot Be Virtual
| Function | Virtual allowed? | Reason |
|---|---|---|
| Ordinary non-static member function | Yes | The normal case |
| Destructor | Yes, and often required | Correct cleanup through a base pointer |
| Constructor | No | The type is known when creating; the vptr is not set up yet |
| Static member function | No | No object, so no dynamic type (see Static Members) |
| Friend / non-member function | No | Not a member; call a virtual member from it instead |
| Member function template | No | The vtable size must be fixed, but a template has unlimited instantiations |
Operator member function (e.g. operator==) | Yes | Operators are just functions |
Common Mistakes
- Missing virtual destructor in a polymorphic base class: deleting through a base pointer is undefined behaviour and typically leaks.
- Signature mismatch without
override: a missingconstsilently creates a new function. Always writeoverride. - Passing polymorphic objects by value: slicing. Use references or pointers.
- Expecting the derived version inside a base constructor: you get the base version.
- Different default arguments in base and derived versions: the static type's default wins.
- Calling a virtual function on an object (not a pointer/reference) and thinking dynamic dispatch was tested.
c.draw()on aCircle cwould callCircle::draweven withoutvirtual. - Using
static_castto downcast when you are not sure of the type: usedynamic_castand check the result.
Interview / Exam Questions
1. What is the difference between compile-time and run-time polymorphism?
Compile-time polymorphism (function overloading, operator overloading, templates) is resolved by the compiler using the static types of arguments. Run-time polymorphism (virtual functions called through base pointers or references) is resolved during execution using the dynamic type of the object, typically via the vtable.
2. Why should a base class have a virtual destructor?
If a derived object is deleted through a base pointer and the base destructor is not virtual, the behaviour is undefined; in practice the derived destructor is skipped and its resources leak. A virtual destructor ensures the derived destructor runs first, followed by the base destructor.
3. Why can't a constructor be virtual?
Virtual dispatch uses the dynamic type of an existing object, but a constructor's job is to create the object, and the caller always names the exact type being created. Also, the vptr is set up during construction. Use a virtual clone() function when you need to copy through a base reference.
4. A class has one int and three virtual functions. What is its likely sizeof on a 64-bit system?
16 bytes: 8 for the single vptr (the number of virtual functions does not matter, they share one vtable per class), 4 for the int, and 4 bytes of padding to keep the size a multiple of the 8-byte alignment. This is implementation-specific; state your assumptions.
5. Base has virtual void f(int x = 1), Derived overrides with void f(int x = 2). What does Base* p = new Derived; p->f(); do?
It calls Derived::f with x = 1. The function is chosen at run time by the dynamic type, but the default argument is chosen at compile time from the static type Base.
6. What is object slicing?
When a derived object is copied into an object of base type (assignment, pass by value, or storing in a container of base objects), only the base part is copied. The result is a genuine base object, so virtual calls on it use the base versions and the derived data is lost. Avoid it by using references or pointers.
7. What happens if a virtual function is called from a base class constructor?
The base class version (more precisely, the version of the class whose constructor is currently running) is called, because the derived part has not been constructed yet. If that function is pure virtual, the behaviour is undefined.
8. What do override and final do?
override (C++11) makes the compiler verify that the function really overrides a base virtual function, catching signature mistakes. final (C++11) on a virtual function forbids further overriding in derived classes; on a class it forbids deriving from that class.
Summary
- Polymorphism means one interface, many behaviours. Compile-time: overloading and templates. Run-time: virtual functions.
- A virtual function called through a base pointer or reference runs the version of the object's dynamic type.
- Write
virtualin the base andoverridein derived classes; usefinalto stop further overriding. - Give every polymorphic base class a virtual destructor; deleting a derived object through a base pointer otherwise is undefined behaviour.
- Typical implementation: one vtable per class, one vptr per object. Cost: one pointer per object plus an indirect call.
- Avoid object slicing: never pass or store polymorphic objects by value.
- Virtual calls in constructors/destructors use the class currently being constructed or destroyed; default arguments come from the static type.
- Covariant return types enable
clone();dynamic_castperforms checked downcasts. - Next, Abstract Classes & Pure Virtual Functions shows how to declare interfaces that derived classes are forced to implement.