Overload new and delete operator

new operator allocates the memory then calls the constructor. delete operator calls the destructor then delete the memory.

As these are operators, so it can be overloaded. But why we need to overload these operators.
* In case, there is lot of allocation and deallocation happens from the heap memory, it can affect the performance. So, to overcome this, we overload the new and delete operator.
* Also, as part of above scenario, heap memory gets fragmented. As a result, even though there is sufficient memory present in heap, still it is not able to give because those memory are not contiguous. To avoid this situation, we overload new and delete operator.

new and delete operator overloading can be done at class as well as global level.

Overload new operator
Takes an argument of type size_t. The value will be calculated automatically by the compiler as per the object size and passed to this argument.

Return type is the void pointer to allocated memory or zero if there is no memory allocated.

Overload delete operator
delete operator takes void pointer as an argument which is pointer to memory allocated by new operator. The reason of having void pointer is because object destructor is called before deallocating the memory, so only memory parts need to be deallocated.

Return type is void

Below is the code snippet for operator overloading of new and delete operator

void* operator new(size_t sz) {
    void* ptr = malloc(sz);
    if (NULL == ptr) {
        cout << “No Free memory is available” << endl;
    }
    return ptr;
}
void operator delete(void* ptr) {
    cout << “Free Memory” << endl;
    free(ptr);
}


Related posts