liveBook · Manning

Dynamic_cast

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

dynamic_cast is a C++ run-time checked cast that converts pointers or references within an inheritance hierarchy and can fail safely for incompatible types.

dynamic_cast performs run-time type checking and pointer conversion within an inheritance hierarchy. When a Book pointer actually refers to Fiction, it produces a Fiction pointer; for a Cookbook, it returns nullptr. section 2.3.3

Filtering a catalogue by subclass

Catalogue::find iterates through Book pointers, casts each one to Fiction, checks for nullptr, then casts its Attributes pointer to FictionAttrs before matching attributes. The same approach handles Cookbook objects.

The cast solves a local type-selection problem but exposes broader design costs:

  • It safely rejects incompatible objects instead of treating every Book as a Fiction. section 2.3.3
  • It adds run-time checks, pointer conversions, subclass pairs, and overloaded operations for each new book kind. section 2.3.3

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

How deep it goes
Explains pointer checking and conversion through a catalogue example, then stops at the resulting design complexity.
Examples
Uses Book, Fiction, Cookbook, Attributes, FictionAttrs, and Catalogue::find as concrete pointer-casting examples.
What it assumes
Assumes basic C++ pointers and inheritance, while demonstrating conversions from base-class pointers to subclass pointers.
What you can do after
Evaluate and understand safe subclass selection while recognizing the coupling and change leaks introduced by repeated casts.
How it connects
Connects inheritance, subclassing, pointers, run-time type checking, pointer conversion, and overloaded catalogue operations.

Also explained in

Compare how 2 books explain dynamic_cast →

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.