0
0
C++programming~5 mins

Destructor role in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Destructor role
O(n)
Understanding Time Complexity

We want to understand how the time cost of a destructor grows as the program runs.

Specifically, how the destructor's work changes when cleaning up objects.

Scenario Under Consideration

Analyze the time complexity of this destructor code.


class MyClass {
  std::string* data;
  int size;
public:
  MyClass(int n) : size(n) { data = new std::string[size]; }
  ~MyClass() { delete[] data; }
};
    

This code creates an array and the destructor frees that array when the object is destroyed.

Identify Repeating Operations

Look at what the destructor does repeatedly.

  • Primary operation: Deleting an array of size n.
  • How many times: Once per object destruction, but the delete[] frees all elements.
How Execution Grows With Input

The destructor frees memory proportional to the array size.

Input Size (n)Approx. Operations
10About 10 steps to free
100About 100 steps to free
1000About 1000 steps to free

Pattern observation: The work grows directly with the size of the array.

Final Time Complexity

Time Complexity: O(n)

This means the destructor takes longer if the array it frees is bigger, growing in a straight line with size.

Common Mistake

[X] Wrong: "Destructor runs instantly no matter the data size."

[OK] Correct: The destructor must free all allocated memory, so if the data is large, it takes more time.

Interview Connect

Knowing how destructors scale helps you write efficient cleanup code and understand program performance better.

Self-Check

"What if the destructor also had to delete multiple arrays inside the object? How would the time complexity change?"