
Understanding Destructors In C++ (OOP)
In C++, a destructor is a special member function of a class that is automatically called when an object goes out of scope or is explicitly deleted. The main purpose of a destructor is to release resources allocated to an object during its lifetime.
Key Characteristics of a Destructor
Contents
- Same Name as the Class:
- A destructor has the same name as the class but is prefixed with a tilde (
~).
- A destructor has the same name as the class but is prefixed with a tilde (
- No Return Type:
- Destructors do not return any value, not even
void.
- Destructors do not return any value, not even
- No Parameters:
- Destructors cannot take arguments or be overloaded.
- Called Automatically:
- When an object goes out of scope (e.g., at the end of a function), the destructor is automatically invoked.
- One Destructor per Class:
- A class can only have one destructor.
Purpose of a Destructor
- Resource Management:
- Release memory or other resources allocated during the lifetime of an object.
- Clean-Up Tasks:
- Perform clean-up actions, such as closing files, freeing dynamic memory, or logging messages.
- Ensure Proper De-allocation:
- Prevent memory leaks and ensure efficient resource utilization.
Class Student Example
class Student {
private:
string rollnum; // Private member: Roll number of the student.
public:
string name; // Public member: Name of the student.
// Constructor
Student(string r, string n) {
cout << "Student data open" << endl;
rollnum = r;
name = n;
}
// Destructor
~Student() {
cout << "Destructor is called" << endl;
}
// Public Function
void show() {
cout << "The name of Student is: " << name << endl;
cout << "The roll number of Student is: " << rollnum << endl;
}
};
Explanation of the Class
- Constructor:
- The constructor
Student(string r, string n)initializes the private memberrollnumand public membername. - A message
"Student data open"is printed when a newStudentobject is created.
- The constructor
- Destructor:
- The destructor
~Student()is automatically called when aStudentobject goes out of scope. - A message
"Destructor is called"is printed, indicating that the resources used by the object are being released.
- The destructor
- Private Member (
rollnum):- Encapsulates the student’s roll number. This can only be accessed and manipulated within the class.
- Public Member (
name):- Represents the student’s name and is accessible outside the class.
- Member Function (
show):- Displays the name and roll number of the student.
Main Function
int main() {
// Creating the first Student object
Student s1("BSSE51S24R030", "Zubair");
s1.show(); // Displaying the details of s1
// Creating the second Student object
Student s2("BSSE51S24R032", "Zaeem");
s2.show(); // Displaying the details of s2
// The destructors will be called automatically for s1 and s2
return 0;
}
Explanation of the Main Function
- Creating Objects (
s1ands2):- Two
Studentobjects are created with roll numbers and names. - The constructor is called for each object, initializing the data members and printing the message
"Student data open".
- Two
- Displaying Data:
- The
show()function is called for boths1ands2to display their details.
- The
- Calling the Destructor:
- When the program exits the
mainfunction, thes1ands2objects go out of scope. - The destructors for both objects are automatically invoked, printing
"Destructor is called".
- When the program exits the
Output
The name of Student is: Zubair
The roll number of Student is: BSSE51S24R030
Student data open
The name of Student is: Zaeem
The roll number of Student is: BSSE51S24R032
Destructor is called
Destructor is called
Explanation of the Output
- Constructor Messages:
"Student data open"is printed twice, once for eachStudentobject (s1ands2), indicating that the constructor has been called.
- Student Details:
- The
show()function prints the name and roll number of each student.
- The
- Destructor Messages:
"Destructor is called"is printed twice, once for eachStudentobject, indicating that the destructor has been invoked when the objects go out of scope.
Understanding When Destructors Are Called
- Scope End:
- Destructors are automatically called when an object goes out of scope. For local variables, this occurs when the block or function ends.
- Explicit Deletion:
- For dynamically allocated objects, the destructor is called when
deleteis used.
- For dynamically allocated objects, the destructor is called when
Key Concepts of Destructors
| Aspect | Explanation |
|---|---|
| Definition | A special member function that cleans up resources when an object is destroyed. |
| Syntax | Prefixed with a tilde (~) and has the same name as the class. |
| Invocation | Automatically called when the object goes out of scope. |
| Usage | To release resources, free memory, or close files. |
| No Arguments | Destructors cannot accept parameters. |
| One Destructor per Class | A class can have only one destructor. |
Conclusion
In this tutorial, we explored the concept of destructors in C++ through the example of a Student class. Destructors play a vital role in resource management by ensuring that resources such as memory and file handles are released when they are no longer needed.
- Why Destructors?
Destructors are especially useful in dynamic memory allocation and file handling to prevent memory leaks and other resource mismanagement issues. - Key Takeaway:
Every object is guaranteed to have its destructor called automatically when it goes out of scope, making destructors a cornerstone of efficient resource management in C++.