Default constructor in C++ - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: Calling the default constructor for each object.
- How many times: Exactly
ntimes, once per object.
Each new object requires one constructor call, so the total work grows directly with the number of objects.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 constructor calls |
| 100 | 100 constructor calls |
| 1000 | 1000 constructor calls |
Pattern observation: Doubling the number of objects doubles the total constructor calls.
Time Complexity: O(n)
This means the time to create all objects grows in a straight line with the number of objects.
[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.
Understanding how object creation scales helps you reason about program speed and resource use in real projects.
"What if the default constructor did some heavy work inside? How would the time complexity change?"