c-plus-plus
  1. c-plus-plus-destructor

C++ Object Class Destructor

Syntax

A destructor is a special member function with the same name as the class preceded by a tilde (~). It is executed automatically when an object of the class is destroyed.

class MyClass {
public:
    // constructor
    MyClass() {
        // Constructor code...
    }
    
    // destructor
    ~MyClass() {
        // Destructor code...
    }
};

Example

#include <iostream>

class Person {
public:
    Person() {
        std::cout << "Constructor called" << std::endl;
    }

    ~Person() {
        std::cout << "Destructor called" << std::endl;
    }
};

int main() {
    Person personObj;

    return 0;
}

Output

Constructor called
Destructor called

Explanation

In the above example, we have defined a class Person with a constructor and a destructor. When the object personObj is created, the constructor is called, and when the object is destroyed, the destructor is called.

Use

A destructor is used to perform cleanup operations before an object is destroyed. Any resources allocated during the object's lifetime should be released in the destructor.

Important Points

  • A destructor is a member function of a class that is executed automatically when an object of that class is destroyed.
  • A destructor has the same name as the class preceded by a tilde (~).
  • A destructor takes no arguments and has no return type.
  • A destructor is called automatically when an object is destroyed, either because it goes out of scope or because it is dynamically allocated and delete is called on it.

Summary

In C++, a destructor is a special member function of a class that is executed automatically when an object of the class is destroyed. It is used to perform cleanup operations before the object is destroyed, releasing any resources allocated during the object's lifetime. A destructor has the same name as the class preceded by a tilde (~). It takes no arguments and has no return type. A destructor is called automatically when an object is destroyed, either because it goes out of scope or because delete is called on it.

Published on: