Destructor in C++
A destructor is a special member function that is automatically invoked when an object is destroyed. It shares the class name prefixed with a tilde (~) and is used for cleanup tasks like deallocating memory. It takes no parameters and cannot be overloaded or inherited.
General Syntax:
class ClassName {
public:
~ClassName(); // Destructor declaration
};
Example:
class Student {
public:
~Student() {
cout << “Object destroyed.”;
}
};
int main() {
Student s;
} // Destructor called here