Skip to main content

Constructor and destructor order, multilevel inheritance

Short answer

In multilevel inheritance, base class constructors are called first from the topmost in the hierarchy, then derived constructors. Destructors are called in the exact reverse order. For hierarchy A→B→C, creating object of C invokes A, B, C constructors; destruction order is C, B, A.

Write a program to show the order of constructor (and destructor) invocation in multilevel inheritance. Show your program outputs.

In inheritance, constructors are called in the order of derivation: base class first, then derived classes (from the top of the hierarchy downwards). Destructors are called in the reverse order. In multilevel inheritance A -> B -> C, creating an object of C calls constructors A, B, C, and destructors C, B, A.

#include <iostream>
using namespace std;

class A {
public:
    A()  { cout << "Constructor of A" << endl; }
    ~A() { cout << "Destructor of A" << endl; }
};

class B : public A {
public:
    B()  { cout << "Constructor of B" << endl; }
    ~B() { cout << "Destructor of B" << endl; }
};

class C : public B {
public:
    C()  { cout << "Constructor of C" << endl; }
    ~C() { cout << "Destructor of C" << endl; }
};

int main() {
    cout << "Creating object of C" << endl;
    C obj;
    cout << "End of main" << endl;
    return 0;
}

Output:

Creating object of C
Constructor of A
Constructor of B
Constructor of C
End of main
Destructor of C
Destructor of B
Destructor of A

The derived constructor cannot finish before its base part exists, so the base is built first. Likewise the base part must be destroyed last, so destruction goes in reverse.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 6 questions →