Polymorphism & virtual Functions in C++
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.
virtual enables overriding
Mark the base function virtual. Derived classes with matching signatures then override it instead of merely hiding it.
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.
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.
Virtual destructors required
A polymorphic base must declare a virtual destructor, or deleting through Base* skips derived cleanup β undefined behavior.
#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;}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself β building beats watching.