In this article we will discuss why we should overload new and delete operator and how to do it.

When we create a new Object on heap by calling new operator then it does following things internally,

  • First it allocates the required memory by calling operator new i.e. operator new returns the pointer top memory.
  • Afterwards, it initializes that memory by calling the constructor of the specified Type.

Similarly when we delete the dynamically allocated memory it does following steps internally,

  • First it de initializes the memory by calling Destructor of the specified Type
  • Afterwards, it removes the allocated memory by calling operator delete.

Now, suppose a new requirement comes i.e. new/delete operator to do some special stuff while allocating memory i.e.

1.) Instead of allocating raw memory from heap every time, use memory from a memory pool i.e. fetch memory from a memory pool and return it after usage
2.) Do some logging, book keeping and decision making while allocating and deallocating memory like, keeping track of how much memory has been used etc.
3.)etc

To achieve this above requirement, we need to overload new and delete operator. Lets see how to do oveload them,

Overloading new and delete at global level

Output:

User Defined :: Operator new
User Defined :: Operator delete
User Defined :: Operator new
Dummy :: Constructor
Dummy :: Destructor
User Defined :: Operator delete
User Defined :: Operator new []
User Defined :: Operator delete[]

 

We need to overload new[] and delete[] along with new & delete to keep dynamic allocation of arrays in synch with other objects.

Now as we can see it overloaded the new and delete operator at global level therefore every object created on heap through new operator was created by our custom overloaded operator. But suppose we want to overload new and delete for a specific class only then how to do it?

Overloading new and delete for a specific Class

Output:

Dummy :: Operator new
Dummy :: Constructor
Dummy :: Destructor
Dummy :: Operator delete

In the next article we will see how to track memory allocated on heap and also do some bookkeeping on it using overloaded new and delete operator.

Click Here to Subscribe for more Articles / Tutorials like this.