Understanding Destructors In C++ (OOP)

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

  1. Same Name as the Class:
    • A destructor has the same name as the class but is prefixed with a tilde (~).
  2. No Return Type:
    • Destructors do not return any value, not even void.
  3. No Parameters:
    • Destructors cannot take arguments or be overloaded.
  4. Called Automatically:
    • When an object goes out of scope (e.g., at the end of a function), the destructor is automatically invoked.
  5. One Destructor per Class:
    • A class can only have one destructor.

Purpose of a Destructor

  1. Resource Management:
    • Release memory or other resources allocated during the lifetime of an object.
  2. Clean-Up Tasks:
    • Perform clean-up actions, such as closing files, freeing dynamic memory, or logging messages.
  3. 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

  1. Constructor:
    • The constructor Student(string r, string n) initializes the private member rollnum and public member name.
    • A message "Student data open" is printed when a new Student object is created.
  2. Destructor:
    • The destructor ~Student() is automatically called when a Student object goes out of scope.
    • A message "Destructor is called" is printed, indicating that the resources used by the object are being released.
  3. Private Member (rollnum):
    • Encapsulates the student’s roll number. This can only be accessed and manipulated within the class.
  4. Public Member (name):
    • Represents the student’s name and is accessible outside the class.
  5. 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

  1. Creating Objects (s1 and s2):
    • Two Student objects 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".
  2. Displaying Data:
    • The show() function is called for both s1 and s2 to display their details.
  3. Calling the Destructor:
    • When the program exits the main function, the s1 and s2 objects go out of scope.
    • The destructors for both objects are automatically invoked, printing "Destructor is called".

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

  1. Constructor Messages:
    • "Student data open" is printed twice, once for each Student object (s1 and s2), indicating that the constructor has been called.
  2. Student Details:
    • The show() function prints the name and roll number of each student.
  3. Destructor Messages:
    • "Destructor is called" is printed twice, once for each Student object, indicating that the destructor has been invoked when the objects go out of scope.

Understanding When Destructors Are Called

  1. Scope End:
    • Destructors are automatically called when an object goes out of scope. For local variables, this occurs when the block or function ends.
  2. Explicit Deletion:
    • For dynamically allocated objects, the destructor is called when delete is used.

Key Concepts of Destructors

AspectExplanation
DefinitionA special member function that cleans up resources when an object is destroyed.
SyntaxPrefixed with a tilde (~) and has the same name as the class.
InvocationAutomatically called when the object goes out of scope.
UsageTo release resources, free memory, or close files.
No ArgumentsDestructors cannot accept parameters.
One Destructor per ClassA 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++.

Leave a Reply

Your email address will not be published. Required fields are marked *