🧹
OOP Basics

Destructors

Object Khatam Hote Waqt Cleanup
💡 Destructor ek "checkout" process hai — ghar (object) chhodne se pehle automatically chalta hai, taaki cleanup ho jaaye (jaise lights off, doors locked) bina manually yaad rakhe.

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 ek "checkout" process hai — ghar (object) chhodne se pehle automatically chalta hai, taaki cleanup ho jaaye (jaise lights off, doors locked) bina manually yaad rakhe.
1 / 2
⚡ झट से Recap
  • 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
इस page में (1 subtopics)

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;
}
⚠️Common Mistake: Base class ka destructor virtual na hona, jab polymorphism use ho rahi ho, ek bahut common real-world bug hai — Derived class ka resource cleanup silently skip ho jaata hai, memory leak ya undefined behavior.