Destructors - heshawacooray/OOP-Heshawa GitHub Wiki
Definition: A destructor is a special method used to clean up or release resources when an object is destroyed. It is called automatically when an object goes out of scope or is explicitly deleted.
Example code:
#include <iostream>
using namespace std;
class Car {
private:
string brand;
int year;
public:
Car(string b, int y) {
brand = b;
year = y;
}
~Car() {
cout << "Car object destroyed!" << endl;
}
void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};
int main() {
Car car1("Toyota", 2020);
car1.display();
return 0; // Destructor is called here when car1 goes out of scope
}