Working of Constructors and Destructors in C++ with Examples
In C++, constructors and destructors are special member functions that manage the beginning and end of an object's lifetime. A constructor is automatically called when an object is initialized, whereas a destructor is automatically called when the object's lifetime ends. Understanding how constructors and destructors work together is essential for learning object-oriented programming, memory management and resource handling in C++.
C++ में Constructor और Destructor ऐसे special member functions हैं, जो object के lifetime की शुरुआत और अंत को manage करते हैं। Constructor object को initialize करता है, जबकि Destructor object का lifetime समाप्त होने पर cleanup operations perform करता है।
1. Working of Constructor in C++
A constructor is automatically invoked when an object is created and initialized.
Its main responsibilities include:
Initializing data members.
Assigning initial values to objects.
Establishing the initial state of an object.
Acquiring resources when required.
C++ में object create होने और initialize होने पर Constructor automatically call होता है। इसका मुख्य कार्य object के data members को initial values देना और object की initial state तैयार करना है।
Example: Working of Constructor
#include <iostream>using namespace std;class Student {int rollNo;float marks;public:Student() {rollNo = 101;marks = 85.5f;cout << "Constructor Called" << endl;}void display() {cout << "Roll Number: " << rollNo << endl;cout << "Marks: " << marks << endl;}};int main() {Student s1;cout << "Student Details:" << endl;s1.display();return 0;}
Output
Constructor CalledStudent Details:Roll Number: 101Marks: 85.5
Explanation
The execution of
main()begins.The statement
Student s1;creates an object.The constructor
Student()is automatically called.The data members
rollNoandmarksare initialized.The
display()function displays the object's data.
इस program में Student s1; statement execute होने पर constructor automatically call होता है। यह rollNo और marks को initialize करता है। इसके बाद display() function object की details दिखाता है।
2. Working of Destructor in C++
A destructor is automatically invoked when an object's lifetime ends.
Its main responsibilities include:
Releasing dynamically allocated memory.
Closing files and other resources.
Releasing acquired locks or connections.
Performing necessary cleanup operations.
C++ में Destructor object का lifetime समाप्त होने पर automatically call होता है। इसका उपयोग dynamically allocated memory और अन्य acquired resources को release करने के लिए किया जाता है।
Example: Working of Destructor
#include <iostream>using namespace std;class Demo {public:Demo() {cout << "Object Created" << endl;}~Demo() {cout << "Object Destroyed" << endl;}};int main() {Demo d1;cout << "Inside Main Function" << endl;return 0;}
Output
Object CreatedInside Main FunctionObject Destroyed
Explanation
The object
d1is created.The constructor is automatically called.
The message "Inside Main Function" is displayed.
When execution leaves
main(), the local objectd1is destroyed.Its destructor is automatically invoked.
जब main() function समाप्त होता है, तब local object d1 का lifetime समाप्त हो जाता है और उसका destructor automatically call होता है।
3. Working of Constructor and Destructor Together
A constructor and destructor work together to manage an object's lifetime.
The constructor is called when an object is initialized.
The object remains alive during its lifetime.
The destructor is called when the object's lifetime ends.
Constructor object की lifetime की शुरुआत में और Destructor उसकी lifetime के अंत में execute होता है।
C++ Program: Constructor and Destructor Together
#include <iostream>using namespace std;class Demo {public:Demo() {cout << "Constructor Called" << endl;}~Demo() {cout << "Destructor Called" << endl;}void display() {cout << "Object is Working" << endl;}};int main() {cout << "Program Started" << endl;Demo obj;obj.display();cout << "Program Ending" << endl;return 0;}
Output
Program StartedConstructor CalledObject is WorkingProgram EndingDestructor Called
Explanation
In this program, the constructor and destructor execute at different stages:
main()begins execution.The message "Program Started" is displayed.
Object
objis created, and its constructor is called.The
display()function is called.The message "Program Ending" is displayed.
The local object
objis destroyed as execution leavesmain().Its destructor is called.
इस program में पहले constructor execute होता है और object को initialize करता है। Object अपना कार्य पूरा करता है। जब main() समाप्त होता है, तब destructor call होकर object के destruction से संबंधित cleanup करता है।
4. Working with Multiple Objects
When multiple local objects are created in the same scope, their constructors are called in the order of their initialization. Their destructors are called in the reverse order when their lifetimes end.
जब एक ही scope में multiple local objects बनाए जाते हैं, तो उनके constructors initialization के क्रम में execute होते हैं। Scope समाप्त होने पर destructors reverse order में execute होते हैं।
C++ Program
#include <iostream>using namespace std;class Demo {int number;public:Demo(int n) {number = n;cout << "Constructor: " << number << endl;}~Demo() {cout << "Destructor: " << number << endl;}};int main() {Demo obj1(10);Demo obj2(20);Demo obj3(30);cout << "Inside Main Function" << endl;return 0;}
Output
Constructor: 10Constructor: 20Constructor: 30Inside Main FunctionDestructor: 30Destructor: 20Destructor: 10
Explanation
The objects are created in this order:
obj1obj2obj3
Therefore, their constructors are called in the same order.
When main() ends, the objects are destroyed in reverse order:
obj3obj2obj1
इस उदाहरण में तीन objects क्रमशः create होते हैं। इसलिए उनके constructors भी उसी क्रम में call होते हैं। लेकिन destruction के समय सबसे बाद में बना object सबसे पहले destroy होता है।
5. Working with Dynamic Objects
Objects created using the new operator have dynamic storage duration. Their destructors are normally called when the corresponding delete expression is executed.
Unlike ordinary local objects, dynamically allocated objects are not automatically destroyed merely because a pointer to them goes out of scope.
new operator से बनाए गए objects dynamically allocated होते हैं। ऐसे objects का destructor सामान्यतः corresponding delete expression execute होने पर call होता है। केवल pointer variable का scope समाप्त होने से dynamically allocated object destroy नहीं होता।
C++ Program
#include <iostream>using namespace std;class Demo {public:Demo() {cout << "Constructor Called" << endl;}~Demo() {cout << "Destructor Called" << endl;}};int main() {Demo* ptr = new Demo;cout << "Dynamic Object Created" << endl;delete ptr;cout << "Dynamic Object Deleted" << endl;return 0;}
Output
Constructor CalledDynamic Object CreatedDestructor CalledDynamic Object Deleted
Explanation
new Demoallocates storage and creates an object.The constructor is automatically called.
The pointer
ptrstores the address of the object.delete ptrdestroys the object.The destructor is automatically called before the object's storage is released.
इस program में new Demo से object create होता है। जब delete ptr execute होता है, तब पहले destructor call होता है और उसके बाद allocated storage release होती है।
6. Working with Constructors and Destructors in Inheritance
In inheritance, constructors and destructors follow a specific execution order.
The base class constructor executes before the derived class constructor.
The derived class destructor executes before the base class destructor.
Inheritance में derived class object create होने पर पहले base class constructor execute होता है और उसके बाद derived class constructor। Destruction के समय इसका क्रम reverse होता है।
C++ Program
#include <iostream>using namespace std;class Base {public:Base() {cout << "Base Constructor" << endl;}~Base() {cout << "Base Destructor" << endl;}};class Derived : public Base {public:Derived() {cout << "Derived Constructor" << endl;}~Derived() {cout << "Derived Destructor" << endl;}};int main() {Derived obj;cout << "Inside Main Function" << endl;return 0;}
Output
Base ConstructorDerived ConstructorInside Main FunctionDerived DestructorBase Destructor
Explanation
When the derived object is created:
The base class constructor is called first.
The derived class constructor is called next.
When the object is destroyed:
The derived class destructor is called first.
The base class destructor is called next.
यहाँ derived class का object बनाने पर पहले Base Constructor और फिर Derived Constructor call होता है। Object destroy होने पर पहले Derived Destructor और फिर Base Destructor call होता है।
Note: When deleting a derived object through a base-class pointer, the base class should generally have a virtual destructor. This ensures that the derived destructor is also invoked correctly.
7. Constructor and Destructor with Dynamic Memory Allocation
Constructors and destructors are commonly used together for resource management.
A constructor can allocate dynamic memory, while the destructor can release that memory when the object is destroyed.
Constructor dynamic memory allocate कर सकता है और Destructor object destroy होने पर उस memory को release कर सकता है।
C++ Program
#include <iostream>using namespace std;class Array {int* arr;int size;public:Array(int s) : size(s) {arr = new int[size];for (int i = 0; i < size; i++) {arr[i] = (i + 1) * 10;}cout << "Memory Allocated" << endl;}void display() {cout << "Array Elements: ";for (int i = 0; i < size; i++) {cout << arr[i] << " ";}cout << endl;}~Array() {delete[] arr;cout << "Memory Released" << endl;}};int main() {Array a1(5);a1.display();return 0;}
Output
Memory AllocatedArray Elements: 10 20 30 40 50Memory Released
Explanation
The object
a1is created with size5.The constructor allocates memory for five integers using
new[].The array elements are initialized.
The
display()function displays the elements.When
main()ends, the destructor is automatically called.The destructor uses
delete[]to release the allocated memory.
इस program में constructor new[] का उपयोग करके array के लिए memory allocate करता है। जब object का lifetime समाप्त होता है, तब destructor delete[] का उपयोग करके memory release करता है।
Modern C++ Note: This example demonstrates manual memory management for learning purposes. In production code, prefer std::vector<int> for dynamically sized arrays. Standard library containers manage their own memory automatically and help avoid resource-management errors. If a class directly owns raw dynamic memory, its copy constructor and copy assignment operator must also be designed carefully.
8. Frequently Asked Questions (FAQs)
Q1. What is the relationship between constructors and destructors in C++?
A constructor initializes an object when it is created, whereas a destructor performs cleanup when the object's lifetime ends.
Constructor object को initialize करता है और Destructor object के lifetime के अंत में cleanup करता है।
Q2. Which is called first, constructor or destructor?
The constructor is called first during object initialization. The destructor is called later when the object's lifetime ends.
Object creation के समय पहले Constructor call होता है और destruction के समय Destructor call होता है।
Q3. Are constructors and destructors called automatically?
Yes. They are automatically invoked as part of object initialization and destruction, subject to the object's lifetime and storage-management rules.
हाँ, object initialization और destruction के दौरान ये automatically invoke होते हैं।
Q4. In what order are constructors and destructors called for multiple local objects?
Constructors are called in the order of object initialization, while destructors are called in reverse order.
Multiple local objects के constructors creation order में और destructors reverse order में call होते हैं।
Q5. Is a destructor called when a pointer goes out of scope?
Not necessarily. If the pointer refers to an object allocated using new, the object remains alive until it is explicitly deleted or otherwise destroyed through a valid ownership mechanism.
नहीं, केवल pointer का scope समाप्त होने से new द्वारा बनाया गया object destroy नहीं होता।
Q6. Can a constructor call a destructor?
A constructor does not normally call the destructor of its own object. C++ manages object construction and destruction according to lifetime rules. If construction fails, already constructed subobjects are destroyed automatically.
Constructor सामान्यतः अपने object का destructor call नहीं करता। यदि construction के दौरान exception आती है, तो पहले से successfully constructed subobjects destroy किए जाते हैं।
Q7. Why are constructors and destructors important in C++?
They help manage object initialization, resource acquisition and cleanup. They are fundamental to RAII and safe resource management.
ये object initialization और resource management को आसान बनाते हैं तथा RAII का आधार हैं।
Constructors and destructors work together to manage the lifetime of objects in C++. Constructors initialize objects and establish their initial state, while destructors perform cleanup when objects are destroyed. They are particularly important when working with multiple objects, dynamic memory allocation, inheritance and resource management.
C++ में Constructor और Destructor object के पूरे lifetime को manage करने में महत्वपूर्ण भूमिका निभाते हैं। Constructor object को initialize करता है और Destructor उसके lifetime के अंत में cleanup करता है। इनकी working समझना Advanced C++ और Object-Oriented Programming के लिए आवश्यक है।
Comments
Post a Comment