liveBook · Manning

Virtual method

As explained in Learn C++ by Example

A virtual function is a C++ member function whose implementation can be selected according to the object's dynamic type through polymorphic dispatch.

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

How Learn C++ by Example covers it

How deep it goes
Explains pure virtual methods, overriding, v-table dispatch, destructor safety, and pointer-based use without detailing compiler-generated layouts.
Examples
Demonstrates StepperBlob, RandomBlob, a Blob race, assertions, random distributions, and a zero-valued test generator.
What it assumes
Assumes basic C++ classes and member functions while teaching abstract classes, overriding, and dispatch through a concrete race.
What you can do after
Build it from scratch by defining a polymorphic Blob interface and implementing interchangeable derived classes with tested behavior.
How it connects
Connects virtual methods to abstract base classes, inheritance, polymorphism, pointers, references, destructors, and smart pointers.

Also explained in

Compare how 3 books explain virtual method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.