Assume that we have constructor functions for both the base class and the…
2012
Assume that we have constructor functions for both the base class and the derived class. Now consider the following declaration inside main():
Base *P = new Derived;In what sequence will the constructors be called?
Answer: B. Base class constructor followed by derived class constructor. — Concept: In C++, construction of an object always proceeds base-first. When a derived-class object is created, its base-class subobject must be completely…
- A.
Derived class constructor followed by Base class constructor.
- B.
Base class constructor followed by derived class constructor.
- C.
Base class constructor will not be called.
- D.
Derived class constructor will not be called.
Attempted by 19 students.
Show answer & explanation
Correct answer: B
Concept: In C++, construction of an object always proceeds base-first. When a derived-class object is created, its base-class subobject must be completely constructed before the derived class's own data members are initialised and its constructor body runs, because the derived constructor is entitled to use the inherited members. The type of the pointer that will hold the object's address is a compile-time (static) matter and has no influence on which constructors run, or in what order.
Application:
The expression new Derived allocates storage for a complete Derived object and begins constructing it. The declared type of the pointer variable, Base *, is only the static type through which the object will later be accessed.
Construction therefore starts with the Base subobject: the Base constructor runs first, invoked either implicitly (its default constructor) or explicitly through the Derived constructor's member-initialiser list.
Only after the Base constructor has returned are the Derived class's own data members initialised and the Derived constructor body executed.
The address of the finished object is then stored in the pointer P. That assignment happens after construction is complete and changes nothing about it.
Cross-check: Destruction runs in exactly the mirror order — the Derived destructor first, then the Base destructor — and that mirror relationship only makes sense if construction is base-first, so the two rules corroborate each other. A separate point: deleting such an object through a Base * pointer when Base's destructor is not declared virtual is undefined behaviour in C++; in practice the Derived destructor is commonly not run at all. That is a destruction concern, not a construction one.
Result: the Base class constructor is called first, followed by the derived class constructor.