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

C++Server Side ProgrammingProgramming

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.


using namespace std;
class MyClass {
      ~MyClass() {
         cout << "Destructor of MyClass" << endl;
int main() {
   MyClass *obj;
   obj = new MyClass();
   delete obj;


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().

Updated on 30-Jul-2019 22:30:26