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

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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

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