In this article we will discuss how new and delete operator works internally in C++.

new operator is used to dynamically allocate memory on heap and delete operator is used to delete the memory from the heap allocated by new operator.

Usage example of new and delete operator is as follows,

Output :
Sample::Constructor
Sample::Destructor

When we create a new object on heap using new operator, it performs 2 operations internally in following order,

  1. In first step new operator allocates the storage of size (sizeof type) on the heap by calling operator new(). operator new() takes the size_t as parameter and returns the pointer of newly allocated memory.
  2. In second stop new operator initialize that memory by calling constructor of passed type/class.

Similarly when we delete a pointer by calling operator delete, it performs 2 operations internally in following order,

  1. In first step delete operator de-initialize that memory by calling destructor of that type/class.
  2. In second step delete operator deallocates the memory from the heap by calling operator delete().

 

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