Learn C++
#include "oopadvanced/polymorphism.hpp"

Polymorphism & virtual Functions in C++

//concept

Polymorphism lets one interface serve many forms: a base-class pointer calling a virtual function runs the derived class's version, decided at run time from the object's true type. Without virtual, the same call binds statically to the base version β€” same syntax, fundamentally different behavior.

The machinery is a per-class vtable the compiler builds for any class with virtuals, adding one pointer per object. That tiny cost buys substitutability: containers of Base* holding mixed derived objects, each behaving as itself through identical calls.

//how it works
1

virtual enables overriding

Mark the base function virtual. Derived classes with matching signatures then override it instead of merely hiding it.

2

Dispatch needs indirection

Polymorphism works through pointers and references only β€” Base* p = new Dog(); p->speak(); runs Dog's speak. Plain Base objects slice away derived parts.

3

Cost: one vtable pointer

Each polymorphic object carries a hidden vptr to its class's virtual table. One indirection per virtual call β€” negligible next to the flexibility.

4

Virtual destructors required

A polymorphic base must declare a virtual destructor, or deleting through Base* skips derived cleanup β€” undefined behavior.

//example
#include <iostream>
#include <string>
Β 
class Animal {
public:
virtual std::string speak() { return "?"; }
virtual ~Animal() = default;
};
Β 
class Dog : public Animal {
public:
std::string speak() override { return "woof"; }
};
Β 
int main() {
Animal* p = new Dog();
std::cout << p->speak() << std::endl;
delete p;
return 0;
}
Output
woof
1p is declared Animal* but points at a Dog β€” the static type says Animal, the dynamic type says Dog.
2Because speak is virtual, the call dispatches through the vtable to Dog::speak at run time, printing woof.
3delete p runs Dog's destructor then Animal's, thanks to the virtual destructor β€” full cleanup chain.
//use cases
Plugin and driver architectures: one base interface, many implementations chosen at run time
Heterogeneous collections (shapes, widgets, enemies) processed through uniform Base* loops
Test doubles: swapping real dependencies for mocks behind the same virtual interface
Frameworks where user code overrides documented virtual hooks

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself β€” building beats watching.