A destructor is a special member function in C++ that is automatically called when an object of a class is destroyed or goes out of scope. It is responsible for performing cleanup tasks, such as deallocating memory and releasing resources that the object may have acquired during its lifetime.
• The destructor has the same name as the class but is prefixed with a tilde (~).
• Example: If the class is ClassName, the destructor is ~ClassName().
• Destructors cannot have parameters.
• They cannot be overloaded or have different versions.
• Destructors do not have a return type, not even void.
• Destructors are called automatically when an object is destroyed or goes out of scope.
• are called automatically when an object is destroyed or goes out of scope.
• Destructors cannot be declared as virtual in a class (although they can be in base classes to ensure proper cleanup in derived classes).
• You cannot apply access modifiers like public, private, or protected to destructors.
class ClassName {
public:
~ClassName() {
// Destructor body
}
};
ClassName::~ClassName() {
// Destructor body
}
<#include <iostream>>
<using namespace std;>
class Example {
private:
int* data;
public:
// Constructor
Example(int value) {
data = new int; // Allocate memory
*data = value; // Initialize value
cout << "Constructor called: " << *data <<
endl;
}
// Destructor
~Example() {
delete data; // Deallocate memory
cout << "Destructor called." << endl;
}
};
int main() {
Example obj1(10); // Constructor is called here
// Other code...
return 0; // Destructor is called automatically here
}
Constructor called: 10
Destructor called.