C++ Destructor

A destructor in C++ is a special member function of a class that is automatically called when an object of that class is destroyed. Its primary purpose is to release resources, clean up, and perform any necessary finalization before the object is removed from memory. Destructors are commonly used for tasks such as deallocating memory, closing file handles, or releasing other system resources that the object may have acquired during its lifetime.

Characteristics of Destructor

1. The destructor has the same name as the class, but preceded by a tilde (~).

2. It does not take any parameters and does not return any value.

3. A class can only have one destructor, and it cannot be overloaded.

4. Destructors are invoked automatically when an object goes out of scope or is explicitly deleted (in case of dynamic memory allocation).

Syntax:


class MyClassExample {
public:
    ~MyClassExample () {  // Destructor
        // Cleanup code, such as releasing resources or memory
    }
};

Example:


#include <iostream>
using namespace std;

class Employee {
public:
    int age;
    // Parameterized constructor
    Employee(int val) {
        age = val;  // Initialize age with the provided value
    }
  
    // Destructor
    ~Employee() {
        cout << "Employee with age " << age << " is being destroyed." << endl;
    }
    void display() {
        cout << "Employee's age = " << age << endl;
    }
};

int main() {
    Employee emp(35);  // Calls parameterized constructor with value 35
    emp.display();  // Output: age = 35
    return 0;
}

Output:

Employee's age = 35
Employee with age 35 is being destroyed.

Explanation:

1. Destructor (~Employee()): This destructor gets called automatically when an object goes out of scope or is explicitly deleted (if dynamically allocated). In this case, it's just printing a message indicating that an Employee object is being destroyed.

2. In the output, when the program ends and the objects emp and emp2 are destroyed, you'll see a message like: Employee with age 35 is being destroyed.