Write a Program to Use Constructors and Destructors in a Class
In C++, constructors and destructors are special member functions used to manage the lifecycle of an object — from its creation to its destruction. Understanding how they work is a key part of mastering object-oriented programming (OOP) in C++.
🔹 What is a Constructor?
A constructor is a special function that is automatically called when an object is created. Its main purpose is to initialize object data members.
Characteristics:
- Has the same name as the class.
- No return type (not even `void`).
- Can be overloaded (i.e., multiple constructors with different parameters).
🔹 What is a Destructor?
A destructor is a special function that is automatically called when an object goes out of scope or is deleted. Its main purpose is to perform clean-up tasks like releasing memory or closing files.
Characteristics:
- Same name as the class, preceded by a tilde (`~`).
- Cannot be overloaded.
- No parameters and no return type.
✅ C++ Program Using Constructor and Destructor
#include <iostream>
using namespace std;
class Student {
private:
string name;
int rollNo;
public:
// Constructor
Student() {
cout << "Constructor called: Object created!" << endl;
name = "Not Assigned";
rollNo = 0;
}
// Parameterized Constructor
Student(string n, int r) {
name = n;
rollNo = r;
cout << "Parameterized Constructor called!" << endl;
}
// Display function
void display() {
cout << "Name: " << name << ", Roll No: " << rollNo << endl;
}
// Destructor
~Student() {
cout << "Destructor called: Object destroyed!" << endl;
}
};
int main() {
cout << "Creating student1 using default constructor...\n";
Student student1;
student1.display();
cout << "\nCreating student2 using parameterized constructor...\n";
Student student2("Vivek Bhardwaj", 101);
student2.display();
cout << "\nEnd of main function.\n";
return 0;
}
🔍 Output Explanation
Creating student1 using default constructor...
Constructor called: Object created!
Name: Not Assigned, Roll No: 0
Creating student2 using parameterized constructor...
Parameterized Constructor called!
Name: Vivek Bhardwaj, Roll No: 101
End of main function.
Destructor called: Object destroyed!
Destructor called: Object destroyed!
- student1 is created using the default constructor.
- student2 is created using the parameterized constructor.
- Both objects are destroyed at the end of the program, triggering the destructor.
✅ Conclusion
Constructors and destructors automate the process of initialization and cleanup in object-oriented programming. They help manage memory and resources efficiently without manual intervention.
- Use constructors to ensure that objects are always created with valid initial states.
- Use destructors to free resources, especially when dealing with file handling, dynamic memory, or complex objects.
Comments
Post a Comment