Skip to content

Destructors

๐Ÿ’ฃ What is a Destructor?

A Destructor is a special member function of a class that is automatically called when an object goes out of scope or is explicitly deleted.

Its main job is to release resources (like memory, files, or database connections) that the object may have acquired during its lifetime.


โœ… Key Features of Destructors:

FeatureDescription
Same name as the classBut with a tilde (~) symbol before it
No argumentsCannot be overloaded
No return typeNot even void
Called automaticallyWhen object is destroyed
Only one per classUnlike constructors, destructors are not overloaded

๐Ÿ”ง Syntax:

class ClassName {
public:
~ClassName() {
// cleanup code
}
};

๐Ÿงช Example: Basic Destructor

#include <iostream>
using namespace std;

class Student {
public:
Student() {
cout << "Constructor called" << endl;
}

~Student() {
cout << "Destructor called" << endl;
}
};

int main() {
Student s1; // Constructor called here
// Destructor will be called automatically when s1 goes out of scope
return 0;
}

๐ŸŽฏ Output:

Constructor called  
Destructor called

๐Ÿง  Real-Life Analogy

Think of a constructor like opening a file or booking a hotel room.
And the destructor is like closing the file or checking out from the hotel โ€” it ensures everything is cleaned up and resources are freed.


๐Ÿงต Why Are Destructors Important?

Especially when you use dynamic memory (new), the destructor helps to:

  • Free allocated memory
  • Close file streams
  • Disconnect database connections
  • Avoid memory leaks

๐Ÿ› ๏ธ Example with Dynamic Memory

class Example {
int* data;

public:
Example() {
data = new int[5]; // Allocate memory
cout << "Memory allocated" << endl;
}

~Example() {
delete[] data; // Free memory
cout << "Memory released" << endl;
}
};

int main() {
Example obj;
return 0;
}

๐ŸŽฏ Output:

Memory allocated  
Memory released

โš ๏ธ Destructor is Called When:

  • Object goes out of scope (e.g., function ends)
  • Object is deleted (if dynamically allocated)
  • Program ends, and objects are cleaned up automatically

๐Ÿ“Œ Summary

  • A destructor is used to release resources used by the object.
  • Automatically invoked when an object is destroyed.
  • Only one destructor per class, and it cannot be overloaded.
  • Very useful in dynamic memory management to prevent memory leaks.