liveBook · Manning

Construction order

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

Construction order is the language-defined ordering in which base-class and derived-class subobjects are initialized when an object is created.

Construction order determines which parts of an inherited C++ object are initialized first. For a three-level hierarchy A, B, and C, creating C initializes the A subobject, then the B subobject, and finally the C subobject. Each constructor begins by invoking its base constructor and resumes only after that constructor completes. section 8.9

This order makes constructor-time virtual calls a maintenance hazard:

  • A base constructor runs before derived-class state has been initialized. section 8.9
  • Virtual-function dispatch reflects the class whose construction is currently completing, rather than automatically using the final derived behavior. section 8.9
  • Calling virtual functions from constructors therefore produces surprising output and can make class invariants difficult to maintain. section 8.9

Mistake: calling virtual functions during construction

A Person constructor calls print(), which calls virtual getHonorific(). Constructing GradStudent prints “Aimee”, then “second year Aimee”, then “candidate Aimee” as Person, Student, and GradStudent constructors run. The safer correction removes constructor-time print calls and leaves printing to code that runs after construction, while preserving the inheritance hierarchy. section 8.9

Figure 8.1 A three-level hierarchy showing construction order

Trace the A-to-B-to-C sequence visually before examining how virtual-function behavior changes at each construction stage. section 8.9

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

How deep it goes
Defines three-level base-to-derived sequencing and gives a conceptual dispatch model, but defers complex implementation details.
Examples
Demonstrates Person, Student, and GradStudent constructors printing progressively different honorifics.
What it assumes
Assumes basic C++ inheritance and constructors while teaching the construction sequence from a three-level hierarchy.
What you can do after
Diagnose/debug with it by tracing base-to-derived constructor execution and removing virtual calls from constructors.
How it connects
Connects inheritance, constructors, virtual functions, and class invariants.

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.