Topic 55 of 83
Inheritance Constructors
Overview
When an object of a derived class is created, the Base class constructor runs FIRST. When it is destroyed, the Derived class destructor runs FIRST (LIFO order).
Syntax
cpp
class Base {
public:
Base() { cout << "Base created\n"; }
~Base() { cout << "Base destroyed\n"; }
};
class Derived : public Base {
public:
Derived() { cout << "Derived created\n"; }
~Derived() { cout << "Derived destroyed\n"; }
};
// Output on creation: Base -> Derived
// Output on destruction: Derived -> BaseCommon Pitfalls
- Forgetting that base constructors are completely unaware of derived classes, so virtual function calls inside constructors do not resolve to the derived implementations.
Interview Tips
- You must explicitly call the base class parameterized constructor from the derived class's initializer list if the base class has no default constructor.
Real-World Example
Passing arguments to a Base constructor.
example
cpp
#include <iostream>
using namespace std;
class Base {
public:
Base(int x) { cout << "Base initialized with " << x << endl; }
};
class Derived : public Base {
public:
// Explicitly calling Base(x)
Derived(int x, int y) : Base(x) {
cout << "Derived initialized with " << y << endl;
}
};
int main() {
Derived d(10, 20);
return 0;
}