C++ Destructor

A destructor is a special member function in C++ that is automatically called when an object of a class is destroyed or goes out of scope. It is responsible for performing cleanup tasks, such as deallocating memory and releasing resources that the object may have acquired during its lifetime.

Key Characteristics of Destructors:

1. Name:

• The destructor has the same name as the class but is prefixed with a tilde (~).

• Example: If the class is ClassName, the destructor is ~ClassName().

2. No Parameters:

• Destructors cannot have parameters.

• They cannot be overloaded or have different versions.

3. No Return Type:

• Destructors do not have a return type, not even void.

4. Automatic Invocation:

• Destructors are called automatically when an object is destroyed or goes out of scope.

5. Automatic Invocation:

• are called automatically when an object is destroyed or goes out of scope.

6. Cannot be Virtual:

• Destructors cannot be declared as virtual in a class (although they can be in base classes to ensure proper cleanup in derived classes).

7. No Modifiers:

• You cannot apply access modifiers like public, private, or protected to destructors.

Syntax of Destructor:

class ClassName {
public:
~ClassName() {
// Destructor body
}
};

Outside a Class:

ClassName::~ClassName() {
// Destructor body
}

Example of Constructor and Destructor:


<#include <iostream>>
<using namespace std;>

class Example {
  private:
    int* data;

  public:
    // Constructor
    Example(int value) {
      data = new int; // Allocate memory
      *data = value; // Initialize value
      cout << "Constructor called: " << *data << endl;
    }

    // Destructor
    ~Example() {
      delete data; // Deallocate memory
      cout << "Destructor called." << endl;
    }
};

int main() {
  Example obj1(10); // Constructor is called here

  // Other code...

  return 0; // Destructor is called automatically here
}

Output:

Constructor called: 10
Destructor called.