Thursday, November 17, 2011

How to Overload new & delete Operators in C++?

Sometimes programmer need to modify the default behaviors of new and delete operators in a customized way. In such cases, these operators can be overloaded to handle memory resources and to increase the efficiency of memory management. Also memory leaks can be detected by overloading new and delete operators. The operator function for new and delete have the following form:
class class_name{
        void *operator new(size_t);
        void *operator delete(void*);
        void *operator new[](size_t);
        void *operator delete[](void*);

Member operator new() and operator delete() are implicitly static member. So , they don’t have this pointer and do not modify an object. Their purpose is memory allocation and de-allocation. For example:
using namespace std;

class CPoint{
        int x;
        int y;
        CPoint(int a, int b):x(a), y(b) {}
        void *operator new (size_t size);
        void *operator new [] (size_t size);
        void operator delete (void *ptr);
        void operator delete[](void *ptr);
        void display();

void CPoint::display(){
void *CPoint::operator new(size_t size){
    cout<<"Overloaded operator new called" <<endl;
    CPoint *ppoint = :: new CPoint;
    return ppoint;

void *CPoint::operator new [](size_t size){
    cout<<"Overloaded operator new [] called"<<endl;
    CPoint *ppoint=::new CPoint[size/sizeof(CPoint)];
            //avoid memory leak: size=sizeof(CPoint)*n
    return ppoint;

void CPoint::operator delete(void *ptr){
    cout<<"Overloaded operator delete called"<<endl;
    ::delete (CPoint*) ptr;

void CPoint::operator delete[](void *ptr){
    cout<<"Overloaded operator delete[] called"<<endl;
    ::delete[] (CPoint*) ptr;

int main(){
    CPoint *p1, *p2;
    p1=new CPoint(2,3);
    p2=new CPoint[5];
    cout<<"Value of PI: ";

    for(int i=0; i<5; ++i){

    for(int i=0; i<5; ++i){
    delete p1;
    delete[] p2;
    return 0;

No comments:

Post a Comment