Bird
Raised Fist0
C++programming~10 mins

Destructor role in C++ - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Destructor role
Object Created
↓
Object Used
↓
Scope Ends or delete called
↓
Destructor Called
↓
Resources Freed
↓
Object Destroyed
When an object is no longer needed, its destructor runs automatically to clean up resources before the object is destroyed.
Execution Sample
C++
#include <iostream>

class MyClass {
public:
  ~MyClass() { std::cout << "Destructor called\n"; }
};

int main() {
  MyClass obj;
}
This code creates an object of MyClass and calls its destructor automatically when main ends.
Execution Table
StepActionEvaluationResult
1Enter main functionStartmain begins
2Create object obj of MyClassConstructor runs (default)obj exists
3Program runs inside mainNo destructor called yetobj usable
4main function endsScope of obj endsTrigger destructor
5Destructor ~MyClass() calledPrints messageOutput: Destructor called
6Object obj destroyedMemory freedobj no longer exists
💡 Object goes out of scope, destructor runs, then program ends
Variable Tracker
VariableStartAfter CreationAfter main ends
objdoes not existexists (in scope)destroyed (out of scope)
Key Moments - 3 Insights
Why does the destructor run automatically without being called explicitly?
The destructor runs automatically when the object goes out of scope or is deleted, as shown in execution_table step 4 and 5.
What happens if the destructor is missing?
If no destructor is defined, C++ provides a default one that does basic cleanup, but custom resource cleanup won't happen.
Does the destructor run before or after the object is destroyed?
The destructor runs before the object is destroyed to free resources, as shown in execution_table step 5 before step 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens at step 5?
Amain function starts
BObject is created
CDestructor is called and prints a message
DObject is destroyed without destructor
💡 Hint
Check the 'Action' and 'Result' columns at step 5 in the execution_table
At which step does the object go out of scope triggering the destructor?
AStep 2
BStep 4
CStep 6
DStep 1
💡 Hint
Look for when 'Scope of obj ends' in the 'Evaluation' column
If the object was created with new, when would the destructor run?
AWhen delete is called on the pointer
BImmediately after creation
CAutomatically at end of main
DNever
💡 Hint
Destructor runs when delete is called for objects created with new, not automatically at scope end
Concept Snapshot
Destructor role in C++:
- Destructor is a special function ~ClassName()
- Runs automatically when object goes out of scope or is deleted
- Cleans up resources like memory or files
- No need to call explicitly
- Helps prevent resource leaks
Full Transcript
In C++, a destructor is a special function that runs automatically when an object is no longer needed. This happens when the object goes out of scope or when delete is called on a pointer to the object. The destructor cleans up resources like memory or files to prevent leaks. In the example, the object 'obj' is created inside main. When main ends, obj goes out of scope, triggering the destructor which prints a message. After that, the object is destroyed and memory is freed. This automatic cleanup is important for safe and efficient programs.

Practice

(1/5)
1. What is the main role of a destructor in C++?
easy
A. To clean up resources when an object is destroyed
B. To create new objects
C. To initialize variables
D. To overload operators

Solution

  1. Step 1: Understand the purpose of a destructor

    A destructor is a special function that runs when an object is destroyed to free resources like memory or files.
  2. Step 2: Compare with other options

    Creating objects, initializing variables, and overloading operators are not roles of destructors.
  3. Final Answer:

    To clean up resources when an object is destroyed -> Option A
  4. Quick Check:

    Destructor role = cleanup [OK]
Hint: Destructor always cleans up when object ends [OK]
Common Mistakes:
  • Confusing destructor with constructor
  • Thinking destructor creates objects
  • Believing destructor initializes variables
2. Which of the following is the correct syntax for a destructor in a class named Car?
easy
A. Car~() {}
B. void ~Car() {}
C. ~Car() {}
D. void Car() {}

Solution

  1. Step 1: Recall destructor syntax

    A destructor has the same name as the class with a tilde (~) prefix and no return type.
  2. Step 2: Check each option

    ~Car() {} matches the correct syntax. void ~Car() {} wrongly includes 'void'. Car~() {} has wrong order. void Car() {} lacks tilde and looks like a constructor.
  3. Final Answer:

    ~Car() {} -> Option C
  4. Quick Check:

    Destructor syntax = ~ClassName() [OK]
Hint: Destructor name = ~ + class name, no return type [OK]
Common Mistakes:
  • Adding return type to destructor
  • Placing tilde after class name
  • Confusing destructor with constructor syntax
3. What will be the output of this C++ code?
class Box {
public:
  Box() { std::cout << "Created\n"; }
  ~Box() { std::cout << "Destroyed\n"; }
};

int main() {
  Box b;
  return 0;
}
medium
A. Destroyed\nCreated\n
B. Created\nDestroyed\n
C. Created\n
D. No output

Solution

  1. Step 1: Trace object creation

    When b is created, constructor prints "Created".
  2. Step 2: Trace object destruction

    At end of main(), b is destroyed, destructor prints "Destroyed".
  3. Final Answer:

    Created\nDestroyed\n -> Option B
  4. Quick Check:

    Constructor then destructor output [OK]
Hint: Constructor runs first, destructor runs last [OK]
Common Mistakes:
  • Assuming destructor runs before constructor
  • Expecting no output
  • Confusing order of prints
4. Identify the error in this destructor code:
class Sample {
public:
  ~Sample(int x) { }
};
medium
A. Destructor cannot have parameters
B. Destructor must return int
C. Destructor name should not have ~
D. Destructor must be static

Solution

  1. Step 1: Check destructor parameters

    Destructors cannot have parameters; they must have empty parentheses.
  2. Step 2: Verify other rules

    Destructor has no return type, must have ~ prefix, and cannot be static.
  3. Final Answer:

    Destructor cannot have parameters -> Option A
  4. Quick Check:

    Destructor params = none [OK]
Hint: Destructor always has empty parentheses [OK]
Common Mistakes:
  • Adding parameters to destructor
  • Adding return type
  • Removing ~ from destructor name
5. Consider a class FileHandler that opens a file in its constructor. Which is the best way to ensure the file is closed properly when the object is no longer needed?
hard
A. Do nothing; files close automatically when program ends
B. Manually call a close method before deleting the object
C. Rely on the operating system to close the file automatically
D. Write a destructor that closes the file

Solution

  1. Step 1: Understand resource management

    Files opened by an object should be closed when the object is destroyed to avoid resource leaks.
  2. Step 2: Use destructor for cleanup

    Destructor runs automatically when object ends, so closing the file there ensures proper cleanup.
  3. Final Answer:

    Write a destructor that closes the file -> Option D
  4. Quick Check:

    Destructor cleans resources automatically [OK]
Hint: Use destructor to free resources automatically [OK]
Common Mistakes:
  • Forgetting to close files causing leaks
  • Relying on manual close calls
  • Assuming OS always cleans up immediately
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard