0
0
C++programming~5 mins

Default constructor in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Default constructor
O(n)
Understanding Time Complexity

We want to understand how long it takes to create an object using a default constructor.

Specifically, how does the time change when we create many objects?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class MyClass {
public:
    MyClass() { /* default constructor */ }
};

int main() {
    const int n = 1000;
    MyClass arr[n];
    return 0;
}
    

This code creates an array of n objects using the default constructor.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the default constructor for each object.
  • How many times: Exactly n times, once per object.
How Execution Grows With Input

Each new object requires one constructor call, so the total work grows directly with the number of objects.

Input Size (n)Approx. Operations
1010 constructor calls
100100 constructor calls
10001000 constructor calls

Pattern observation: Doubling the number of objects doubles the total constructor calls.

Final Time Complexity

Time Complexity: O(n)

This means the time to create all objects grows in a straight line with the number of objects.

Common Mistake

[X] Wrong: "Creating many objects with a default constructor is instant and does not depend on how many objects there are."

[OK] Correct: Each object still needs its constructor called, so more objects mean more work and more time.

Interview Connect

Understanding how object creation scales helps you reason about program speed and resource use in real projects.

Self-Check

"What if the default constructor did some heavy work inside? How would the time complexity change?"