In this C++ tutorial, you will learn about Class Destructor, how to define it, and how it works, with example programs.

C++ Destructor

C++ Destructor is a function in a class that is called when an object instance of this class type is destroyed.

There are two types of destructors based on whether the destructor is explicitly defined in a class or not.

  • Default Destructor
  • User-defined Destructor

Syntax

The syntax of a destructor function for a class A is

~A() {
    //body
}

Please notice the tilda symbol ~ before the destructor name.

Programmer has to remember the following points while creating a user defined destructor.

  • Name of destructor must be same as that of class.
  • There can be only one destructor defined for a class.
  • A destructor must be declared public.
  • A destructor cannot be static or const.
  • A destructor function does not have any parameters.
  • A destructor function does not have any return type.
ADVERTISEMENT

Default Destructor

If there is not destructor defined in the class, compiler creates a default destructor for the class.

Example

For example, in the following program, we have a class A defined with no destructor. But, when an object instance of this type has to be destroyed, compiler calls the default destructor implicitly.

C++ Program

#include <iostream>
using namespace std;

class A {
public:
    int x;
    A(int _x) {
        x = _x;
    }
};

void function1() {
    A a1(3);
}

int main() {
    function1();
}

In this program, we created an object a1 of type A in function1(). When the program control comes out of function1(), the scope of a1 is ended. Since the object becomes obsolete, the compiler destroys it. Since, we have not defined a destructor in class A, compiler creates a default destructor and takes care of the object with destruction.

User-defined Destructor

Programmer has a choice to define a destructor. In fact, it is a good idea to define a destructor when the class objects has pointers or has dynamically allocated memory. Because, a default destructor does not free the pointer or dynamically allocated memory, and this may result in memory leak.

Example

In the following program, we define a class with a pointer as a member. In the destructor function, we des

C++ Program

#include <iostream>
using namespace std;

class A {
public:
    char* x;
    ~A() {
        delete x;
        cout << "Object destroyed successfully." << endl;
    }
};

void function1() {
    A a1 = A();
    char* y = new char[1024];
    a1.x = y;
}

int main() {
    function1();
}

Output

Object destroyed successfully.
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned what a destructor is, what are its properties, when is the destructor invoked, what compiler does when there is no default destructor, and how to define a destructor and override default behaviour, with the help of examples.