๐ฃ 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:
Feature | Description |
---|---|
Same name as the class | But with a tilde (~) symbol before it |
No arguments | Cannot be overloaded |
No return type | Not even void |
Called automatically | When object is destroyed |
Only one per class | Unlike 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.