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?"
Practice
Solution
Step 1: Understand automatic object lifecycle
Automatic objects are created when their scope starts and destroyed when their scope ends.Step 2: Identify destructor call timing
The destructor is called automatically when the object goes out of scope to clean up resources.Final Answer:
When the object goes out of scope -> Option BQuick Check:
Destructor called at scope end = When object goes out of scope [OK]
- Thinking destructor runs at object creation
- Believing manual deletion is needed for local objects
- Confusing program start with object destruction
Car in C++?Solution
Step 1: Recall destructor syntax
Destructor syntax uses a tilde (~) followed by the class name and parentheses.Step 2: Match correct option
~Car(); matches the correct syntax:~Car();Final Answer:
~Car(); -> Option DQuick Check:
Destructor syntax = ~ClassName() [OK]
- Using void return type for destructor
- Writing destructor with class scope resolution in declaration
- Using keyword 'destructor' which doesn't exist
class Test {
public:
Test() { std::cout << "Created "; }
~Test() { std::cout << "Destroyed "; }
};
int main() {
Test t1;
{
Test t2;
}
return 0;
}Solution
Step 1: Trace object creation
First,t1is created: prints "Created ". Then inside inner scope,t2is created: prints another "Created ".Step 2: Trace object destruction
When inner scope ends,t2is destroyed: prints "Destroyed ". Then at program end,t1is destroyed: prints "Destroyed ".Final Answer:
Created Created Destroyed Destroyed -> Option AQuick Check:
Constructor and destructor calls match output [OK]
- Assuming destruction happens immediately after creation
- Forgetting inner scope destruction before outer
- Mixing order of constructor and destructor prints
class Sample {
public:
Sample() { std::cout << "Start "; }
~Sample() { std::cout << "End "; }
};
int main() {
Sample* p = new Sample();
// Missing delete p;
return 0;
}What is the problem with this code?
Solution
Step 1: Identify dynamic object creation
The object is created withnew, so it lives on the heap and needs manual deletion.Step 2: Check for destructor call
Sincedelete p;is missing, destructor is never called, causing a memory leak.Final Answer:
Memory leak because destructor is not called -> Option CQuick Check:
Missing delete on new object = memory leak [OK]
- Assuming destructor runs automatically for new objects
- Thinking missing delete causes syntax error
- Believing destructor is called twice
Box currently exist during program execution. Which approach correctly uses constructors and destructors to maintain this count?Solution
Step 1: Understand object counting logic
To track live objects, increase count when object is created and decrease when destroyed.Step 2: Use static counter in class
A static variable shared by all objects can hold the count, incremented in constructor and decremented in destructor.Final Answer:
Increment a static counter in constructor and decrement it in destructor -> Option AQuick Check:
Static counter + constructor increment + destructor decrement = correct count [OK]
- Changing count only in constructor or destructor, not both
- Using global variable instead of static class member
- Reversing increment and decrement roles
Ready to prove it?
Pass the test and this pattern moves unknown
