Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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


1 Answer
Smita Kapse

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.