Object creation and destruction flow in C++ - Time & Space Complexity
We want to understand how the time taken by a program changes when it creates and destroys objects.
How does the number of objects affect the total time spent on these actions?
Analyze the time complexity of the following code snippet.
class MyClass {
public:
MyClass() { /* constructor work */ }
~MyClass() { /* destructor work */ }
};
void createObjects(int n) {
for (int i = 0; i < n; ++i) {
MyClass obj;
}
}
This code creates and destroys n objects one after another inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating and destroying one object inside the loop.
- How many times: Exactly
ntimes, once per loop iteration.
Each object creation and destruction takes some fixed time. Doing this n times means the total time grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations + 10 destructions = 20 operations |
| 100 | 100 creations + 100 destructions = 200 operations |
| 1000 | 1000 creations + 1000 destructions = 2000 operations |
Pattern observation: When n doubles, total operations roughly double too.
Time Complexity: O(n)
This means the total time grows in a straight line as the number of objects increases.
[X] Wrong: "Creating and destroying objects inside a loop is constant time because each object is small."
[OK] Correct: Even if each object is small, doing it many times adds up. The total time depends on how many objects you create and destroy.
Understanding how object creation and destruction scale helps you reason about program speed and resource use in real projects.
What if we created objects dynamically with new inside the loop and deleted them after? How would the time complexity change?
Practice
Solution
Step 1: Understand constructor timing
Constructors are special functions that run automatically when an object is created to initialize it.Step 2: Understand destructor timing
Destructors run when an object is destroyed or goes out of scope, not before creation.Final Answer:
Constructors are called automatically when an object is created. -> Option CQuick Check:
Constructor = on creation [OK]
- Confusing when constructors and destructors run
- Thinking destructors run before creation
- Believing constructors run on destruction
Car in C++?Solution
Step 1: Recall destructor syntax
In C++, a destructor is declared with a tilde (~) followed by the class name and parentheses, no return type.Step 2: Check options
~Car(); matches the correct syntax:~Car();. Others are invalid syntax.Final Answer:
~Car(); -> Option AQuick Check:
Destructor syntax = ~ClassName() [OK]
- Adding return type to destructor
- Using wrong keywords like 'destructor'
- Confusing constructor syntax with destructor
class Test {
public:
Test() { std::cout << "C"; }
~Test() { std::cout << "D"; }
};
int main() {
Test t1;
{
Test t2;
}
std::cout << "E";
return 0;
}What is the output when this program runs?
Solution
Step 1: Trace object creation
t1 is created first, prints 'C'. Then t2 is created inside inner block, prints another 'C'.Step 2: Trace object destruction and output
When inner block ends, t2 is destroyed, prints 'D'. Then 'E' is printed. Finally, t1 is destroyed at program end, prints 'D'.Final Answer:
CCDED -> Option BQuick Check:
Creation C twice, destruction D twice, E in middle [OK]
- Forgetting destructor runs at block end
- Mixing order of destruction
- Ignoring output inside main
class Sample {
public:
Sample() { std::cout << "Created"; }
void ~Sample() { std::cout << "Destroyed"; }
};
int main() {
Sample s;
return 0;
}Solution
Step 1: Check destructor declaration
Destructor must not have a return type. Here, 'void' before '~Sample()' is invalid syntax.Step 2: Verify other options
Destructor name is correct with '~Sample'. Constructors have no return type but that is correct here. Destructors cannot be static.Final Answer:
Destructor has a return type which is not allowed. -> Option AQuick Check:
Destructor = no return type [OK]
- Adding void or other return types to destructor
- Misnaming destructor
- Making destructor static
Resource that opens a file in its constructor and closes it in its destructor. Which of the following code snippets correctly ensures the file is closed automatically when the object goes out of scope?Solution
Step 1: Understand automatic destruction
Objects created on stack (like 'Resource r;') are destroyed automatically when going out of scope, calling destructor to close file.Step 2: Analyze dynamic allocation
Objects created with 'new' must be deleted manually; otherwise destructor won't run automatically, risking resource leaks.Final Answer:
void useFile() { Resource r; // use file } // file closed here automatically -> Option DQuick Check:
Stack objects auto-destroyed, heap objects need delete [OK]
- Forgetting to delete heap objects
- Trying to delete stack objects
- Assuming destructor runs without delete on heap
Ready to prove it?
Pass the test and this pattern moves unknown
