Object lifecycle in C++ - Time & Space Complexity
When we create and destroy objects in C++, the time it takes depends on how many objects we handle.
We want to know how the time grows as we make more objects.
Analyze the time complexity of the following code snippet.
class MyObject {
public:
MyObject() { /* constructor work */ }
~MyObject() { /* destructor work */ }
};
void createObjects(int n) {
MyObject* arr = new MyObject[n];
delete[] arr;
}
This code creates an array of n objects and then deletes them, calling constructors and destructors.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the constructor and destructor for each object.
- How many times: Exactly
ntimes each, once per object.
As the number of objects n increases, the total work grows in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (10 constructions + 10 destructions) |
| 100 | About 200 (100 constructions + 100 destructions) |
| 1000 | About 2000 (1000 constructions + 1000 destructions) |
Pattern observation: The total work doubles the number of objects because each object is constructed and then destroyed.
Time Complexity: O(n)
This means the time to create and destroy objects grows linearly with the number of objects.
[X] Wrong: "Creating many objects takes the same time as creating just one because constructors are fast."
[OK] Correct: Even if each constructor is fast, doing it many times adds up, so total time grows with the number of objects.
Understanding how object creation and destruction scale helps you write efficient code and explain performance clearly in real projects.
"What if the destructor does extra work that depends on the size of the object? How would the time complexity change?"