Constructor एक special function होता है जो किसी class का object बनते ही automatic कॉल हो जाता है। इसका काम object की शुरुवाती (initial) value सेट करना होता है। Constructor का नाम हमेशा class के नाम के समान होता है और इसका कोई return type नहीं होता।
Destructor भी एक special function होता है जो तब कॉल होता है जब object का lifetime खत्म हो जाता है, यानी जब वह memory से delete हो रहा होता है। इसका काम resource cleanup करना या आखिरी काम करना होता है। Destructor का नाम class के नाम के सामने tilde (~) लगाकर लिखा जाता है, और इसका भी कोई return type नहीं होता।
#include <iostream>
using namespace std;
class Student {
public:
string name;
int age;
// Constructor
Student(string n, int a) {
name = n;
age = a;
cout << "Constructor called for " << name << endl;
}
// Destructor
~Student() {
cout << "Destructor called for " << name << endl;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
Student s1("Rahul", 20);
s1.display();
Student s2("Anita", 22);
s2.display();
return 0;
}
जब प्रोग्राम चलेगा, तो constructor दोनों objects के लिए कॉल होगा, और प्रोग्राम के अंत में destructor भी कॉल होगा। उदाहरण के लिए:
Constructor called for Rahul
Name: Rahul, Age: 20
Constructor called for Anita
Name: Anita, Age: 22
Destructor called for Anita
Destructor called for Rahul
~
होता है।