Overloading new and delete operator in C++

We can overload new and delete operator in C++.

There are 2 ways to overload.

1. Locally Overloading new and delete operator

2. Globally Overloading new and delete operator

Syntax for new operator overload:

void* operator new(size_t size);

1. Locally Overloading new and delete operator

#include <iostream>
// for more tutorials check www.prodevelopertutorial.com
using namespace std;

class MyClass 
{ 
    int num; 
public: 
    MyClass(){ 
    }
    
    MyClass(int a):num(a) 
    { 

    } 
    void display() 
    { 
        cout<< "num:" << num << endl; 
    } 
    void * operator new(size_t size) 
    { 
        cout<< "Overloading new operator with size: " << size << endl; 
        void * p = ::new MyClass();  
        //void * p = malloc(size); will also work fine 
      
        return p; 
    } 
  
    void operator delete(void * p) 
    { 
        cout<< "Overloading delete operator " << endl; 
        free(p); 
    } 
}; 
  
int main() 
{ 
    MyClass * p = new MyClass(24); 
  
    p->display(); 
    delete p; 
} 

Output:

Overloading new operator with size: 4
num:24
Overloading delete operator

2. Globally Overloading new and delete operator

#include <iostream>
// for more tutorials check www.prodevelopertutorial.com
using namespace std;

class MyClass 
{ 
    int num; 
public: 
    MyClass(){ 
    }
    MyClass(int a):num(a) 
    { 

    } 
    void display() 
    { 
        cout<< "num:" << num << endl; 
    } 

}; 


void * operator new(size_t size) 
{ 
    cout << "New operator overloading " << endl; 
    void * p = malloc(size); 
    return p; 
} 
  
void operator delete(void * p) 
{ 
    cout << "Delete operator overloading " << endl; 
    free(p); 
} 
  
int main() 
{ 
    MyClass * p = new MyClass(24); 
  
    p->display(); 
    delete p; 
} 

Output:

New operator overloading
num:24
Delete operator overloading
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *