Destructors are special member functions in C++ that are automatically called when an object is destroyed. They are used to clean up resources that were allocated by the object during its lifetime.
Syntax
class MyClass {
public:
~MyClass(); // Destructor declaration
};
When Destructors Are Called
Object deletion: When an object is explicitly deleted using the delete operator.
Scope exit: When an object goes out of scope at the end of a block or function.
Program termination: When the program terminates, all objects with destructors are automatically destroyed.
Example
#include <iostream>
using namespace std;
class Person {
public:
string name;
Person(string name) {
this->name = name;
cout << "Constructor called for " << name << endl;
}
~Person() {
cout << "Destructor called for " << name << endl;
}
};
int main() {
Person p1("Alice");
Person p2("Bob");
// p1 and p2 go out of scope here, destructors are called
return 0;
}
Output:
Constructor called for Alice
Constructor called for Bob
Destructor called for Bob
Destructor called for Alice
Custom Destructors
You can define custom destructors to perform specific cleanup tasks. For example, if an object allocates memory on the heap, the destructor can be used to free that memory.
#include <iostream>
using namespace std;
class MyClass {
public:
int* data;
MyClass() {
data = new int[10];
}
~MyClass() {
delete[] data;
cout << "Destructor called" << endl;
}
};
Key Points
Destructors are automatically called when objects are destroyed.
Destructors can be used to clean up resources allocated by the object.
Custom destructors can be defined to perform specific cleanup tasks.
It's important to handle memory management carefully in classes that allocate resources on the heap.
By understanding destructors, you can ensure that your C++ programs properly clean up resources and avoid memory leaks.
Comments