Write simple program to overload new and delete operator in C++

(Last Updated On: March 17, 2018)

Answer includes a simple program to overload new and delete operator in C++ class with important points about overloaded new and delete. Below is the C++ code example program for overloading new and delete operator.

C++ syntax for overloading new and delete is simple. The new operator will accept object size in its parameter and will return a void pointer. The delete operator will accept the pointer do be freed and does not return anything, means return void.

Now if we create an object of the class overloaded new and delete operator function will be called for memory allocation rather than directly requesting memory to operating system.

 

 

NOTES:

If above question is asked then please don’t forget to mention below points.

Important Points/properties: new and delete operator overloading
  • Overloaded new operator can accept additional arguments except size to be allocated.
  • In one class delete operator can be overloaded only once.
  • In one class new operator can be overloaded multiple times.
  • When we create object of the class with “new” operator the class overloaded new function will get called with the object size as a parameter. e.g. CustomMemory object = new CustomMemory.
C++ program example – Overloaded new operator multiple times:
Output:
Custom memory allocation
Constructor
Destructor
Custom memory de- allocation
Custom 2 argument memory allocation
Constructor
Value of i =5
Destructor
Custom memory de- allocation