Destructors
Destructor bhi ek special member function hai — class ke naam jaisa, lekin ~ (tilde) prefix ke saath, koi return type nahi, koi parameters nahi. Ye automatically call hota hai jab object scope se bahar jaata hai (stack objects ke liye) ya delete kiya jaata hai (heap objects ke liye).
Destructor ka sabse common use hai resource cleanup — agar constructor ne kuch allocate kiya tha (heap memory, file handle, network connection), destructor use release karta hai. Ye "RAII" (Resource Acquisition Is Initialization) pattern ka core hai, jo C++ mein memory-safety ka bada hissa hai.
class FileHandler {
public:
FileHandler() {
cout << "File khula" << endl;
}
~FileHandler() {
cout << "File automatically band ho gayi" << endl; // cleanup
}
};
int main() {
FileHandler fh; // constructor chalega: "File khula"
cout << "Kaam kar rahe hain..." << endl;
} // scope khatam — destructor automatically chalega: "File automatically band ho gayi"- Destructor = ~ClassName(), automatically chalta hai object destroy hote hi
- Resource cleanup (memory, files) ke liye use hota hai
- RAII pattern ka foundation — C++ ki memory-safety philosophy
Agar class polymorphically use hoti hai (base class pointer se derived class object delete kiya jaata hai), destructor ko virtual banana ZAROORI hai — warna sirf base class ka destructor chalega, derived class ka resource cleanup miss ho jaayega ("partial destruction" bug).
class Base {
public:
virtual ~Base() { // virtual — zaroori polymorphism ke liye
cout << "Base destroyed" << endl;
}
};
class Derived : public Base {
public:
~Derived() {
cout << "Derived destroyed" << endl;
}
};
int main() {
Base *b = new Derived();
delete b; // virtual destructor ke bina, sirf "Base destroyed" print hota — BUG
// virtual ke saath: dono print hote hain, sahi order mein
return 0;
}