• Home
  • Destructors in C++

Destructors in C++

In C++, a destructor is a special member function of a class that is called automatically when an object of that class goes out of scope or is explicitly deleted. It is used to deallocate memory, close files, and perform any other cleanup activities that are necessary before an object is destroyed.

The syntax for declaring a destructor is similar to the syntax for declaring a constructor, except that the destructor function has a tilde (~) symbol as the first character of its name. Here is an example of how to declare a destructor for a class in C++:

class MyClass {
public:
MyClass(); // constructor
~MyClass(); // destructor
};

Like a constructor, a destructor has no return type and cannot take any arguments. It is called automatically when an object of the class goes out of scope or is deleted, and it is typically used to release any resources that the object was holding, such as memory, file handles, or network connections.

Here is an example of how to define a destructor for a class in C++:

MyClass::~MyClass() {
// cleanup code goes here
}

It is important to note that a destructor is called only once for each object, when the object is destroyed. If an object is created dynamically using the new operator, it must be explicitly deleted using the delete operator to invoke the destructor and deallocate the memory.

MyClass* p = new MyClass();
// use p
delete p; // calls the destructor for p

Destructors are an important feature of C++, as they allow you to clean up resources and release memory when an object is no longer needed. They are an essential part of object-oriented programming in C++.