A virtual method lets a call through a base-class pointer or reference select the implementation belonging to the object’s dynamic type. In a blob-racing game, every Blob can define step and total_steps while each derived blob supplies its own behavior. section 6.1.1 section 6.2.1
Listing 6.1 A first attempt at a base class
namespace Race
{
class Blob
{
public:
virtual void step() = 0; #1
virtual int total_steps() const = 0; #2
};
}
A pure virtual declaration uses = 0, making Blob an abstract base class that cannot be instantiated directly. section 6.1.1
Derived classes override the virtual methods with their own rules. StepperBlob advances by two on every step, while a RandomBlob obtains its increment from a generator and distribution. The override specifier lets the compiler catch a mismatched signature, including a forgotten const; final prevents further overrides. section 6.1.2 section 6.2.1
Two blobs in one race
A collection can treat StepperBlob and RandomBlob as Blob objects, then call blob->step() for each one. Virtual dispatch selects the correct step implementation without changing the race loop. Raw pointers require manual deletion; smart pointers address that ownership burden. section 6.2.1
Under the hood, virtual methods use a table of virtual function pointers, commonly called a v-table, to find the overridden function. A polymorphic base class should also provide a virtual destructor when objects may be deleted through base pointers. section 6.1.1


