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 Called
Student Details:
Roll Number: 101
Marks: 85.5

Explanation

  1. The execution of main() begins.

  2. The statement Student s1; creates an object.

  3. The constructor Student() is automatically called.

  4. The data members rollNo and marks are initialized.

  5. 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 Created
Inside Main Function
Object Destroyed

Explanation

  1. The object d1 is created.

  2. The constructor is automatically called.

  3. The message "Inside Main Function" is displayed.

  4. When execution leaves main(), the local object d1 is destroyed.

  5. 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 Started
Constructor Called
Object is Working
Program Ending
Destructor Called

Explanation

In this program, the constructor and destructor execute at different stages:

  1. main() begins execution.

  2. The message "Program Started" is displayed.

  3. Object obj is created, and its constructor is called.

  4. The display() function is called.

  5. The message "Program Ending" is displayed.

  6. The local object obj is destroyed as execution leaves main().

  7. 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: 10
Constructor: 20
Constructor: 30
Inside Main Function
Destructor: 30
Destructor: 20
Destructor: 10

Explanation

The objects are created in this order:

  1. obj1

  2. obj2

  3. obj3

Therefore, their constructors are called in the same order.

When main() ends, the objects are destroyed in reverse order:

  1. obj3

  2. obj2

  3. obj1

इस उदाहरण में तीन 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 Called
Dynamic Object Created
Destructor Called
Dynamic Object Deleted

Explanation

  1. new Demo allocates storage and creates an object.

  2. The constructor is automatically called.

  3. The pointer ptr stores the address of the object.

  4. delete ptr destroys the object.

  5. 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 Constructor
Derived Constructor
Inside Main Function
Derived Destructor
Base Destructor

Explanation

When the derived object is created:

  1. The base class constructor is called first.

  2. The derived class constructor is called next.

When the object is destroyed:

  1. The derived class destructor is called first.

  2. 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 Allocated
Array Elements: 10 20 30 40 50
Memory Released

Explanation

  1. The object a1 is created with size 5.

  2. The constructor allocates memory for five integers using new[].

  3. The array elements are initialized.

  4. The display() function displays the elements.

  5. When main() ends, the destructor is automatically called.

  6. 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

Popular posts from this blog

Important Questions (IMP) of Programming Methodologies and Data structures using C++ with OOP's Concepts

Complete C++ Programming Course - OOP and Modern C++

OOP's using CPP Syllabus AND Programming Methodologies and Data Structures Using C++ (NEP 2020)