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
