Open In App

new vs operator new in C++

When you create a new object, memory is allocated using operator new function and then the constructor is invoked to initialize the memory. Here, The new operator does both the allocation and the initialization, where as the operator new only does the allocation. Let us see how these both work individually.

new keyword



The new operator is an operator which denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable. When you create an object of class using new keyword(normal new).




// CPP program to illustrate
// use of new keyword
#include<iostream>
using namespace std;
class car
{
    string name;
    int num;
 
    public:
        car(string a, int n)
        {
            cout << "Constructor called" << endl;
            this ->name = a;
            this ->num = n;
        }
 
        void enter()
        {
            cin>>name;
            cin>>num;
        }
 
        void display()
        {
            cout << "Name: " << name << endl;
            cout << "Num: " << num << endl;
        }
};
 
int main()
{
    // Using new keyword
    car *p = new car("Honda", 2017);
    p->display();
}

Output:



Constructor called
Name: Honda
Num: 2017

Operator new

Operator new is a function that allocates raw memory and conceptually a bit similar to malloc().




// CPP program to illustrate
// use of operator new
#include<iostream>
#include<stdlib.h>
 
using namespace std;
 
class car
{
    string name;
    int num;
 
    public:
 
        car(string a, int n)
        {
            cout << "Constructor called" << endl;
            this->name = a;
            this->num = n;
        }
 
        void display()
        {
            cout << "Name: " << name << endl;
            cout << "Num: " << num << endl;
        }
 
        void *operator new(size_t size)
        {
            cout << "new operator overloaded" << endl;
            void *p = malloc(size);
            return p;
        }
 
        void operator delete(void *ptr)
        {
            cout << "delete operator overloaded" << endl;
            free(ptr);
        }
};
 
int main()
{
    car *p = new car("HYUNDAI", 2012);
    p->display();
    delete p;
}

Output:

new operator overloaded
Constructor called
Name:HYUNDAI
Num:2012
delete operator overloaded

New operator vs operator new

  1. Operator vs function: new is an operator as well as a keyword whereas operator new is only a function.
  2. New calls “Operator new”: “new operator” calls “operator new()” , like the way + operator calls operator +()
  3. “Operator new” can be Overloaded: Operator new can be overloaded just like functions allowing us to do customized tasks.
  4. Memory allocation: ‘new expression’ call ‘operator new’ to allocate raw memory, then call constructor.

Article Tags :