Constructors and Destructors

Introduction

C++ में objects का creation और destruction program के execution का महत्वपूर्ण हिस्सा होता है। जब भी कोई object बनता है, तब उसके data को initialize करना आवश्यक होता है, और जब object का काम समाप्त हो जाता है, तब उससे जुड़ी memory को मुक्त (free) करना भी जरूरी होता है।

इन दोनों कार्यों को संभालने के लिए C++ में special member functions का उपयोग किया जाता है, जिन्हें Constructor और Destructor कहा जाता है। Constructor object के निर्माण के समय अपने आप call होता है, जबकि Destructor object के समाप्त होने पर स्वतः execute होता है।

Definition

Constructor

Constructor एक special member function होता है जो object के creation के समय automatically call होता है और object के data members को initialize करता है।

Destructor

Destructor एक special member function होता है जो object के destroy होने पर automatically call होता है और resources या memory को free करता है।

Constructor की विशेषताएँ

  • इसका नाम class के नाम के समान होता है
  • इसका कोई return type नहीं होता
  • object create होते ही automatically call होता है
  • data initialization के लिए उपयोग होता है

Destructor की विशेषताएँ

  • इसका नाम class के नाम के पहले ~ लगाकर बनाया जाता है
  • इसका कोई return type नहीं होता
  • object destroy होते समय automatically call होता है
  • memory या resources को free करने के लिए उपयोग होता है

Constructor का Syntax

class ClassName {
public:
ClassName() {
// constructor body
}
};

Destructor का Syntax

class ClassName {
public:
~ClassName() {
// destructor body
}
};

C++ में Constructor और Destructor का उदाहरण

#include <iostream>
using namespace std;class Demo {
public:
Demo() {
cout << "Constructor Called" << endl;
}

~Demo() {
cout << "Destructor Called";
}
};

int main() {
Demo d1; // object creation

return 0;
}

Output:

Constructor Called
Destructor Called

Working को समझना

  • Demo d1; → object create हुआ
  • Constructor automatically call हुआ
  • Program समाप्त होते ही object destroy हुआ
  • Destructor automatically call हुआ

Constructor के प्रकार (संक्षेप में)

  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor

Destructor के बारे में महत्वपूर्ण बातें

  • एक class में केवल एक destructor होता है
  • इसमें parameters नहीं होते
  • इसे manually call नहीं किया जाता

Constructor और Destructor में अंतर

आधारConstructorDestructor
कार्यInitializationCleanup
Call TimeObject creationObject destruction
SymbolClassName()~ClassName()
NumberMultiple हो सकते हैंकेवल एक

निष्कर्ष

Constructor और Destructor C++ के महत्वपूर्ण special functions हैं जो object के lifecycle को नियंत्रित करते हैं। Constructor object को initialize करता है, जबकि Destructor resources को मुक्त करके program को efficient और सुरक्षित बनाता है।

Leave a Comment

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

Scroll to Top