liveBook · Manning

Pure virtual member function

As explained in Learn C++ by Example

A pure virtual function is a virtual member function declared without an implementation requirement in its declaring class, making that class abstract unless overridden.

A pure virtual member function is declared with virtual and = 0. It keeps the declaring class abstract while requiring derived classes to provide their own implementation. section 6.1.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 small Blob interface declares step and total_steps as pure virtual functions, creating a polymorphic base for different blob types. section 6.1.1

Because Blob has abstract functions, it cannot be instantiated directly. Derived classes become concrete by implementing each function with the exact same signature; override lets the compiler check that match. section 6.1.1 section 6.1.2

A stepping blob

StepperBlob overrides step to increase its private y value by two and overrides total_steps to return y. A small assertion verifies that one step produces two total steps. section 6.1.2

Virtual dispatch uses a v-table when a virtual function is called through a pointer or reference, allowing different derived classes to supply different behavior. section 6.1.1

How Learn C++ by Example covers it

How deep it goes
Explains declaration, abstractness, overriding, and v-table dispatch, while deferring broader special-member-function details.
Examples
Uses a Blob race, a StepperBlob implementation, pointer-based dispatch, and an assertion checking two-step movement.
What it assumes
Assumes basic classes and inheritance while teaching abstract functions, virtual dispatch, and override checking through a small example.
What you can do after
Build it from scratch as an abstract C++ interface and implement checked concrete subclasses.
How it connects
Connects pure virtual functions to abstract base classes, virtual functions, polymorphism, overriding, and virtual destructors.

Also explained in

Compare how 2 books explain pure virtual member function →

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.