Constructor calling order in C++ - Time & Space Complexity
When creating objects in C++, constructors run in a specific order. Understanding this order helps us see how the program spends time during object creation.
We want to know how the time to create an object grows when there are multiple classes involved.
Analyze the time complexity of the constructor calling order in this example.
class Base {
public:
Base() { /* some work */ }
};
class Derived : public Base {
public:
Derived() { /* some work */ }
};
int main() {
Derived obj;
}
This code creates a Derived object, which first calls the Base constructor, then the Derived constructor.
Look for constructor calls and their order.
- Primary operation: Calling constructors of Base and Derived classes.
- How many times: Each constructor is called once per object creation.
Each object creation calls constructors in a fixed sequence.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 | 2 (Base + Derived constructor calls) |
| 10 | 20 (10 x 2 constructor calls) |
| 100 | 200 (100 x 2 constructor calls) |
Pattern observation: The total constructor calls grow linearly with the number of objects created.
Time Complexity: O(n)
This means the time to create n objects grows directly in proportion to n.
[X] Wrong: "The Base constructor runs multiple times per Derived object creation."
[OK] Correct: Each object creation calls the Base constructor exactly once before the Derived constructor.
Knowing constructor calling order and its time impact helps you explain object creation clearly and confidently in interviews.
"What if Derived inherited from multiple Base classes? How would the constructor calling order and time complexity change?"