liveBook · Manning

Polymorphism

As explained in Learn C++ by Example

Polymorphism is the ability to invoke a common interface while allowing the actual object's type to determine the implementation.

Polymorphism lets code invoke a common interface while the object supplies its own implementation. In the blob-racing example, every blob can step and report its total steps, even when the blobs use different movement rules. section 6.1.1

The C++ pattern works through a small set of rules:

  • Declare shared operations as virtual pure functions using = 0; this makes Blob abstract, so it cannot be instantiated directly. section 6.1.1
  • Implement the operations in derived classes, allowing each blob to define its own step behavior. section 6.1.1
  • Call a virtual function through a pointer or reference to Blob; the v-table selects the overridden function for the actual object. section 6.1.1
  • Store different derived blobs behind a common base-pointer type to make them compete in one race; smart pointers avoid manual deletion. section 6.2.1

Different movement rules, one race

RandomBlob derives from Blob and receives a generator and distribution. One instance can use a uniform distribution from 0 to 4, while another uses a normal distribution with mean 2.0 and standard deviation 1.0. Both still respond to step() and total_steps(). A deterministic generator returning zero provides a simple test of the same interface.

How Learn C++ by Example covers it

How deep it goes
Explains abstract interfaces, overriding, v-table dispatch, virtual destructors, and pointer ownership, stopping short of a complete race implementation.
Examples
Demonstrates racing stepper and random blobs, configuring uniform or normal movement, and testing with deterministic zero-producing callables.
What it assumes
Assumes basic C++ classes and pointers while introducing abstract classes, virtual dispatch, special member functions, and smart pointers.
What you can do after
Build polymorphic C++ classes, dispatch through base pointers, combine derived objects, and test implementations with controlled generators.
How it connects
Connects abstract base classes, inheritance, virtual functions, v-tables, pointers, smart pointers, templates, and random distributions.

Also explained in

Compare how 9 books explain polymorphism →

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.