Virtual Destructors

Introduction

Object Oriented Programming में जब inheritance और dynamic binding का उपयोग किया जाता है, तब object destruction (object का समाप्त होना) सही तरीके से होना बहुत महत्वपूर्ण होता है। यदि base class pointer के माध्यम से derived class object को delete किया जाता है, तो यह आवश्यक है कि पहले derived class का destructor और फिर base class का destructor call हो।

यदि destructor को virtual नहीं बनाया जाता, तो केवल base class का destructor call होता है, जिससे memory leak या incomplete cleanup की समस्या हो सकती है। इस समस्या को हल करने के लिए C++ में virtual destructors का उपयोग किया जाता है।


Definition

Virtual Destructor वह destructor होता है जिसे base class में virtual keyword के साथ declare किया जाता है, ताकि derived class object को delete करते समय सभी destructors सही क्रम में call हों।


Syntax

class Base {
public:
virtual ~Base() {
// destructor
}
};

Example (Without Virtual Destructor)

#include <iostream>
using namespace std;class Base {
public:
~Base() {
cout << "Base Destructor" << endl;
}
};

class Derived : public Base {
public:
~Derived() {
cout << "Derived Destructor" << endl;
}
};

int main() {
Base *ptr = new Derived;

delete ptr;
return 0;
}

Output:

Base Destructor

यहाँ Derived class का destructor call नहीं हुआ।


Example (With Virtual Destructor)

#include <iostream>
using namespace std;class Base {
public:
virtual ~Base() {
cout << "Base Destructor" << endl;
}
};

class Derived : public Base {
public:
~Derived() {
cout << "Derived Destructor" << endl;
}
};

int main() {
Base *ptr = new Derived;

delete ptr;

return 0;
}

Output:

Derived Destructor
Base Destructor

Working को समझना

  • Base *ptr = new Derived; → base pointer derived object को point कर रहा है
  • delete ptr; → object destroy किया जा रहा है
  • virtual destructor होने पर:
    • पहले derived destructor call होता है
    • फिर base destructor call होता है

Virtual Destructor के लाभ

  • Proper memory cleanup सुनिश्चित करता है
  • Memory leak से बचाता है
  • Polymorphism के साथ सही behavior देता है
  • Object destruction को safe बनाता है

Important Points

  • Destructor को virtual बनाना चाहिए जब base class का उपयोग polymorphism में हो
  • Virtual destructor हमेशा base class में define किया जाता है
  • Derived class का destructor automatically call होता है

निष्कर्ष

Virtual destructors C++ में inheritance और polymorphism के साथ सुरक्षित object destruction सुनिश्चित करते हैं। यह सुनिश्चित करते हैं कि सभी destructors सही क्रम में execute हों और program memory safe बना रहे।

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top