When an object is manipulated through a pointer or reference to its base class, C++ uses Virtual Functions to ensure the derived class's implementation is executed at runtime.
#include <iostream>
// Abstract Base Class (Cannot be directly instantiated!)
class Shape {
public:
// Pure virtual function
virtual void draw() const = 0;
// MANDATORY: Virtual Destructor
virtual ~Shape() { std::cout << "Shape destroyed\n"; }
};
class Circle : public Shape {
public:
void draw() const override {
std::cout << "Drawing a smooth Circle\n";
}
~Circle() override { std::cout << "Circle cleaned up\n"; }
};
int main() {
Shape* s = new Circle();
s->draw(); // Dispatches dynamically to Circle::draw()!
delete s; // Safely calls Circle destructor then Shape destructor!
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Overview of dynamic vs static dispatch.
Understanding destructor chains.
How dynamic_cast uses VTable RTTI information.