Destructor ek special function hota hai jo automatically call hota hai jab object destroy hota hai (ya program end hota hai).
| Feature | Value |
|---|---|
| Function Name | ~ClassName() (tilde + class name) |
| Return Type | ❌ None (no return type, not even void) |
| Arguments | ❌ Nahi leta (no parameters) |
| Call Timing | Automatically call hota hai jab object delete hota hai |
cpp
CopyEdit
class ClassName {
public:
// Destructor
~ClassName() {
// Cleanup code
}
};
cpp
CopyEdit
#include<iostream>
using namespace std;
class Student {
public:
Student() {
cout << "Constructor called" << endl;
}
~Student() {
cout << "Destructor called" << endl;
}
};
int main() {
Student s1; // Constructor called
// At the end of main(), object s1 will be destroyed
return 0; // Destructor automatically called here
}
🟢 Output:
sql
CopyEdit
Constructor called
Destructor called
| Real Life | Programming |
|---|---|
| Tum room me aaye | Constructor called |
| Tum room se chale gaye | Destructor called (lights off, clean up) |