- Asked 2/10
- 2070 Asar · 4 marks
- 2068 Chaitra · 5 marks
Constructor/destructor order; parameterized base constructor
Short answer
In single inheritance, base constructor runs before derived; destructors reverse. In multiple inheritance, base constructors execute in the order they are listed in the derived class declaration, then derived. Destructors run in reverse. A parameterized base constructor is called using the member initializer list, e.g., Derived(int x) : Base(x).
Explain the constructor and destructor invocation order in single and multiple inheritance. Also show how a parameterized base class constructor is called when derived class object is created.
Single inheritance
Base class constructor runs first, then the derived class constructor. Destructors run in reverse: derived first, then base.
Multiple inheritance
Base class constructors are called in the order in which the bases are listed in the derived class declaration (not the order in the initializer list), then the derived constructor. Destructors run in the exact reverse order.
class D : public A, public B { ... }; // order: A(), B(), D()
// destructors: ~D(), ~B(), ~A()
Passing arguments to a parameterized base constructor
The derived constructor passes values to the base constructor using a member initializer list after a colon. If the base class has no default constructor, this is compulsory.
#include <iostream>
using namespace std;
class A {
int a;
public:
A(int x) { a = x; cout << "A(" << a << ")" << endl; }
~A() { cout << "~A" << endl; }
};
class B {
int b;
public:
B(int y) { b = y; cout << "B(" << b << ")" << endl; }
~B() { cout << "~B" << endl; }
};
class D : public A, public B {
int d;
public:
// arguments for bases are passed in the initializer list
D(int x, int y, int z) : B(y), A(x) {
d = z;
cout << "D(" << d << ")" << endl;
}
~D() { cout << "~D" << endl; }
};
int main() {
D obj(1, 2, 3);
return 0;
}
Output:
A(1)
B(2)
D(3)
~D
~B
~A
Although B(y) is written before A(x) in the initializer list, A is constructed first because A is listed first in class D : public A, public B.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Constructor and destructor order, multilevel inheritance · Object Oriented Programming, chapter 6 · asked 2×
- Department class constructor and destructor · Object Oriented Programming, chapter 4
- Access overridden members from derived class · Object Oriented Programming, chapter 6 · asked 2×
- Ambiguity in multiple inheritance · Object Oriented Programming, chapter 6
- Object adapter and CORBA invocation · Distributed System, chapter 4