0
0
C++programming~5 mins

Constructor calling order in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Constructor calling order
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

Each object creation calls constructors in a fixed sequence.

Input Size (n)Approx. Operations
12 (Base + Derived constructor calls)
1020 (10 x 2 constructor calls)
100200 (100 x 2 constructor calls)

Pattern observation: The total constructor calls grow linearly with the number of objects created.

Final Time Complexity

Time Complexity: O(n)

This means the time to create n objects grows directly in proportion to n.

Common Mistake

[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.

Interview Connect

Knowing constructor calling order and its time impact helps you explain object creation clearly and confidently in interviews.

Self-Check

"What if Derived inherited from multiple Base classes? How would the constructor calling order and time complexity change?"