Inheritance Constructors
Overview
When you create a Child object, a fascinating physical sequence occurs in memory. The CPU cannot build the Child until the Parent exists. Therefore, the Parent's Constructor always executes FIRST, followed immediately by the Child's Constructor.
However, if the Parent Class requires specific data to be built (e.g., a Parameterized Constructor like Entity(int hp)), the Child Class is mathematically obligated to pass that data up to the Parent before it can finish building itself. You accomplish this using a 'Member Initializer List'.
Syntax
#include <iostream>
class Entity {
public:
// Parent requires data to be built!
Entity(int hp) {
std::cout << "Entity built with HP: " << hp << "\n";
}
};
class Player : public Entity {
public:
// Child Constructor MUST route data to the Parent Constructor
// using the Initializer List syntax (: Entity(hp))
Player(int hp, int mana) : Entity(hp) {
std::cout << "Player built with Mana: " << mana << "\n";
}
};
int main() {
// 1. Entity Constructor runs FIRST
// 2. Player Constructor runs SECOND
Player p1(100, 50);
return 0;
}Common Pitfalls
- Failing to initialize a Parameterized Parent. If the Parent Class has no Default Constructor, and the Child Class forgets to pass data up using the Initializer List, the C++ compiler will throw a massive fatal error, as it physically cannot construct the Parent.
Interview Questions
Destructors execute strictly Bottom-Up (Child first, then Parent). When an object dies, the Child's specific memory is torn down first. Once the Child is fully destroyed, the CPU moves up and destroys the foundational Parent memory.
Real-World Example
Routing parameters from a highly specific child class all the way up to a generalized base class.
#include <iostream>
#include <string>
class Employee {
protected:
std::string companyName;
public:
Employee(std::string name) : companyName(name) {}
};
class Manager : public Employee {
public:
// Manager receives the company name and instantly hands it to Employee
Manager(std::string cName) : Employee(cName) {
std::cout << "Manager created for " << companyName << "\n";
}
};Check Your Knowledge
Test your understanding of Inheritance Constructors with these quick questions.