Set your Publisher ID in src/config/ads.ts to display live ads.
Inheritance, Virtual Functions & Polymorphism
The virtual keyword, vtable dynamic dispatch, override, and pure virtual interfaces
Polymorphism in C++ allows derived classes to override base class methods using virtual. The compiler builds a Virtual Method Table (vtable) for dynamic runtime dispatch.
Virtual Functions and Pure Virtual Interfaces
virtual void speak(): Informs the compiler to resolve method calls at runtime based on the actual object type, not the pointer type.
override specifier: Ensures compile-time checking that a method genuinely overrides a base virtual method.
Pure Virtual Function (virtual void run() = 0;): Makes the class abstract, functioning like an Interface that cannot be instantiated directly.
#include <iostream>
#include <vector>
// Abstract Base Class (Pure Virtual Interface)
class Shape {
public:
virtual double area() const = 0; // Pure virtual function
virtual ~Shape() = default; // Always declare virtual destructors in base classes!
};
class Rectangle : public Shape {
private:
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const override { return width * height; }
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override { return 3.14159 * radius * radius; }
};Always declare base class destructors as virtual (virtual ~Base() = default;) so derived class destructors are properly invoked when deleting through base pointers.
Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
Why must base classes designed for polymorphic inheritance always declare a `virtual` destructor in C++?