Constructor and Destructor in Inheritance
Constructors and destructors are not inherited like normal member functions, but they are called automatically when derived objects are created and destroyed.
Constructor Order
When a derived object is created:
- Base class constructor runs first.
- Derived class constructor runs second.
Reason: the base part must be ready before the derived part can use it.
Destructor Order
When a derived object is destroyed:
- Derived class destructor runs first.
- Base class destructor runs second.
Reason: the derived part should clean itself before the base part disappears.
Complete Example
#include <iostream>
using namespace std;
class Base {
public:
Base() {
cout << "Base constructor" << endl;
}
~Base() {
cout << "Base destructor" << endl;
}
};
class Derived : public Base {
public:
Derived() {
cout << "Derived constructor" << endl;
}
~Derived() {
cout << "Derived destructor" << endl;
}
};
int main() {
Derived d;
return 0;
}
Output:
Base constructor
Derived constructor
Derived destructor
Base destructor
Passing Parameters to Base Constructor
If the base class has a parameterized constructor, the derived constructor should call it in the initializer list.
#include <iostream>
#include <string>
using namespace std;
class Person {
protected:
string name;
public:
Person(string personName) : name(personName) {}
};
class Employee : public Person {
private:
int salary;
public:
Employee(string employeeName, int employeeSalary)
: Person(employeeName), salary(employeeSalary) {}
void display() const {
cout << name << " earns " << salary << endl;
}
};
int main() {
Employee employee("Rahim", 50000);
employee.display();
return 0;
}
Multiple Inheritance Order
For multiple inheritance, base constructors run in the order of the inheritance list.
class C : public A, public B { };
Order:
A -> B -> C
Destruction happens in reverse:
C -> B -> A
Viva Answer
In inheritance, base class constructors are called before derived class constructors. Destructors are called in reverse order: derived destructor first, then base destructor. In multiple inheritance, base constructors follow the order written in the inheritance list.
Quick Check
- Which constructor runs first: base or derived?
- Which destructor runs first: base or derived?
- In
class C : public A, public B, which base constructor runs first?