What is the difference between a destructor and a free function in C++?


Here we will see what are the differences between destructor and the free() functions in C++. The destructor is used to perform some action, just before the object is destroyed. This action may not freeing up the memory, but can do some simple action such as displaying one message on screen.

The free() function is used in C, in C++, we can do the same thing using delete keyword also. When the object is deleted using free() or delete, the destructor is invoked. The destructor function takes no argument and returns nothing. This function is called when free or delete is used, or object goes out of scope.

Example

#include<iostream>
#include<cstdlib>
using namespace std;
class MyClass {
   public:
      ~MyClass() {
         cout << "Destructor of MyClass" << endl;
      }
};
int main() {
   MyClass *obj;
   obj = new MyClass();
   delete obj;
}

Output

Destructor of MyClass

Sometimes the free() function may not call the destructor, but delete the content from memory. So here we have used delete keyword in the place of free().

raja
Published on 08-May-2019 08:49:44
Advertisements