Parameterized constructor in C++ - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: Assigning values to object properties inside the constructor.
- How many times: Once per object creation.
Each time we create a new object, the constructor runs once to set values.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 30 assignments |
| 100 | 300 assignments |
| 1000 | 3000 assignments |
Pattern observation: The work grows directly with the number of objects created.
Time Complexity: O(n)
This means if you create more objects, the total time grows in a straight line with how many you make.
[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.
Understanding how object creation time grows helps you write efficient code and explain your reasoning clearly in interviews.
"What if the constructor also called a function that loops over a list? How would the time complexity change?"