Difference between "new operator" and "operator new" in C++?


In C++ when we want to create a new object, we have to create a memory block into the memory, then also call constructor to initialize the memory block. We can create memory element by using the new keyword. This new operator is doing two consecutive task. But the operator new just only create memory space.

New Keyword

The new operator is a special type of operator, which denotes a request for memory allocation on the heap section. When sufficient memory is available, then only new operators initializes the memory to the pointer variable. When we create an object using a normal new keyword it performs two consecutive tasks

  • ? Allocate memory block for the object into the heap section
  • ? Call the constructor to initialize the memory block.

Example Code

#include <iostream>
using namespace std;
class Box {
   public:
   Box() {
      cout << "Constructor called!" <<endl;
   }
};
int main() {
   Box* myBox = new Box;
}

Output

Constructor called!

Operator New

The operator new is a function. This function is used to overload the new operator. Using this we can allocate raw memory block. This is conceptually similar to the malloc() or calloc() functions. This function does not call the constructor so memory is not initialized. However after returning the pointer from this overloaded method, the compiler calls the constructor after that.

Example Code

#include <iostream>
#include <cstdlib>
using namespace std;
class Box {
   public:
   Box() {
      cout << "Constructor called!" <<endl;
   }
   void *operator new(size_t size) {
      cout << "Call Operator New"<<endl;
      void *p = malloc(size);
      return p;
   }
};
int main() {
   Box* myBox = new Box;
}

Output

Call Operator New
Constructor called!

Updated on: 30-Jul-2019

780 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements