0
0
C++programming~5 mins

Parameterized constructor in C++ - Time & Space Complexity

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

Let's see how long it takes to create an object using a parameterized constructor.

We want to know how the time changes when we create many objects with parameters.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class Box {
public:
    int length, width, height;
    Box(int l, int w, int h) {
        length = l;
        width = w;
        height = h;
    }
};

int main() {
    Box b(10, 20, 30);
    return 0;
}

This code creates one Box object using a parameterized constructor that sets its dimensions.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Assigning values to object properties inside the constructor.
  • How many times: Once per object creation.
How Execution Grows With Input

Each time we create a new object, the constructor runs once to set values.

Input Size (n)Approx. Operations
1030 assignments
100300 assignments
10003000 assignments

Pattern observation: The work grows directly with the number of objects created.

Final Time Complexity

Time Complexity: O(n)

This means if you create more objects, the total time grows in a straight line with how many you make.

Common Mistake

[X] Wrong: "Creating an object with parameters takes the same time no matter how many objects are made."

[OK] Correct: Each object needs its own constructor call, so more objects mean more total work.

Interview Connect

Understanding how object creation time grows helps you write efficient code and explain your reasoning clearly in interviews.

Self-Check

"What if the constructor also called a function that loops over a list? How would the time complexity change?"