In C++, a destructor is a special member function of a class that is called automatically when an object goes out of scope or is explicitly deleted. Its main purpose is to release resources that the object may have acquired during its lifetime.
~
).class MyClass {
public:
~MyClass() {
// Cleanup code
}
};
#include <iostream>
class MyClass {
public:
int* data;
// Constructor
MyClass(int size) {
data = new int[size];
std::cout << "Constructor: Memory allocated." << std::endl;
}
// Destructor
~MyClass() {
delete[] data;
std::cout << "Destructor: Memory deallocated." << std::endl;
}
};
int main() {
MyClass obj(10);
return 0;
}
delete
is called on a dynamically allocated object.If a class has virtual functions, it should also have a virtual destructor to ensure proper cleanup when dealing with polymorphism.
class Base {
public:
virtual ~Base() {
std::cout << "Base destructor" << std::endl;
}
};
class Derived : public Base {
public:
~Derived() {
std::cout << "Derived destructor" << std::endl;
}
};
int main() {
Base* obj = new Derived();
delete obj; // Correctly calls Derived and then Base destructor
return 0;
}