liveBook · Manning

Polymorphism

As explained in Object-Oriented Software Design in C++

Polymorphism is the ability for an object's behavior to vary according to the concrete subclass of the object being referenced.

Polymorphism lets code call a common interface while the referenced object's concrete subclass supplies the behavior. In C++, a subclass overrides a superclass member function when both functions share the same signature. section 1.8 section 7.1.1

Tax calculation through a superclass pointer

Declare amount_owed() virtual in GeneralTax, then override it in LocalTax and MaxTax. A GeneralTax* pointing to a LocalTax or MaxTax object dispatches amount_owed() at run time to the matching subclass implementation. The same call can therefore produce general, local, or combined tax calculations without changing the calling code. section 7.1.1

Use polymorphism to:

  • Code to an interface that supports multiple subclasses instead of coupling callers to one concrete subclass. section 2.4
  • Extend behavior through overriding while keeping existing calling code stable. section 2.4
  • Avoid unnecessary subclass hierarchies when simpler data structures would reduce complexity. section 2.4

How Object-Oriented Software Design in C++ covers it

How deep it goes
Explains signatures, overriding, virtual functions, pointers, and runtime dispatch through a tax example.
Examples
Demonstrates GeneralTax, LocalTax, and MaxTax calculating different amounts through GeneralTax pointers.
What it assumes
Assumes familiarity with classes, inheritance, pointers, member functions, and superclass-subclass relationships.
What you can do after
Apply it via C++ virtual functions and subclass overrides to support runtime-varying behavior.
How it connects
Connects inheritance, function overriding, encapsulation, abstraction, and the Code to the Interface Principle.

Also explained in

Compare how 9 books explain polymorphism →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Object-Oriented Software Design in C++. The section links point to the parts of the book it draws on.