Introduction
C++ में जब inheritance का उपयोग किया जाता है, तब constructors और destructors का behavior बहुत महत्वपूर्ण हो जाता है।
Derived class का object बनाते समय base class का constructor पहले execute होता है, और object destroy करते समय destructor reverse order में call होता है।
यह mechanism ensure करता है कि object सही तरीके से initialize और destroy हो।
Definition
Inheritance में constructors और destructors का उपयोग base class और derived class के objects को initialize और destroy करने के लिए किया जाता है, जहाँ execution का एक fixed order follow होता है।
Concept
- Object creation के समय:
- Base class constructor पहले call होता है
- Derived class constructor बाद में call होता है
- Object destruction के समय:
- Derived class destructor पहले call होता है
- Base class destructor बाद में call होता है
Example
#include <iostream>
using namespace std;class Base {
public:
Base() {
cout << "Base Constructor Called" << endl;
} ~Base() {
cout << "Base Destructor Called" << endl;
}
};class Derived : public Base {
public:
Derived() {
cout << "Derived Constructor Called" << endl;
} ~Derived() {
cout << "Derived Destructor Called" << endl;
}
};int main() {
Derived d;
return 0;
}
Output
Base Constructor Called
Derived Constructor Called
Derived Destructor Called
Base Destructor Called
Explanation
- Object create हुआ → पहले
Baseconstructor चला - फिर
Derivedconstructor execute हुआ - Program end होने पर:
- पहले
Deriveddestructor call हुआ - फिर
Basedestructor call हुआ
- पहले
यह order automatic होता है और programmer को manually control नहीं करना पड़ता।
Constructor Passing (Base Constructor with Parameters)
Derived class से base class constructor को call किया जा सकता है:
class Base {
public:
Base(int x) {
cout << "Value: " << x << endl;
}
};class Derived : public Base {
public:
Derived(int a) : Base(a) {
cout << "Derived Constructor" << endl;
}
};
Important Points
- Base constructor हमेशा पहले execute होता है
- Destructor reverse order में execute होता है
- Initialization list का उपयोग करके base constructor call किया जाता है
- Proper initialization के लिए यह concept बहुत जरूरी है
निष्कर्ष
Constructors और destructors inheritance में object lifecycle को manage करते हैं। उनका execution order program की correctness और memory management के लिए बहुत महत्वपूर्ण होता है।