liveBook · Manning

Run-time polymorphism

As explained in 100 C++ Mistakes and How to Avoid Them

Runtime polymorphism is the selection of an overridden operation according to an object's dynamic type during execution.

Run-time polymorphism lets related classes share an interface while each derived type supplies its own operation. A Shape can expose area while Circle provides the type-specific computation. section 8.9

The mistake is calling virtual functions from constructors or destructors. A Person, Student, and GradStudent hierarchy prints progressively more specific honorifics during construction, producing “Aimee,” “second year Aimee,” and “candidate Aimee” rather than one final dynamic result. Keep construction free of virtual calls; let the fully constructed object use polymorphic behavior afterward. section 8.9

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Defines overriding and conceptual dispatch, then stops short of prescribing compiler-specific implementation details.
Examples
Uses Shape/Circle area behavior and a Person/Student/GradStudent constructor hierarchy.
What it assumes
Builds from base classes, derived classes, interfaces, overriding, and virtual functions.
What you can do after
Diagnose unsafe constructor dispatch and remove virtual calls through incremental class-maintenance changes.
How it connects
Connects inheritance, abstraction, interfaces, virtual functions, constructors, and destructors.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.