Overloading New and Delete operator in c++
Last Updated :
18 Oct, 2022
The new and delete operators can also be overloaded like other operators in C++. New and Delete operators can be overloaded globally or they can be overloaded for specific classes.
- If these operators are overloaded using member function for a class, it means that these operators are overloaded only for that specific class.
- If overloading is done outside a class (i.e. it is not a member function of a class), the overloaded ‘new’ and ‘delete’ will be called anytime you make use of these operators (within classes or outside classes). This is global overloading.
The syntax for overloading the new operator :
void* operator new(size_t size);
The overloaded new operator receives size of type size_t, which specifies the number of bytes of memory to be allocated. The return type of the overloaded new must be void*.The overloaded function returns a pointer to the beginning of the block of memory allocated.
Syntax for overloading the delete operator :
void operator delete(void*);
The function receives a parameter of type void* which has to be deleted. Function should not return anything.
NOTE: Both overloaded new and delete operator functions are static members by default. Therefore, they don't have access to this pointer .
Overloading new and delete operator for a specific class:
CPP
// CPP program to demonstrate
// Overloading new and delete operator
// for a specific class
#include<iostream>
#include<stdlib.h>
using namespace std;
class student
{
string name;
int age;
public:
student()
{
cout<< "Constructor is called\n" ;
}
student(string name, int age)
{
this->name = name;
this->age = age;
}
void display()
{
cout<< "Name:" << name << endl;
cout<< "Age:" << age << endl;
}
void * operator new(size_t size)
{
cout<< "Overloading new operator with size: " << size << endl;
void * p = ::operator new(size);
//void * p = malloc(size); will also work fine
return p;
}
void operator delete(void * p)
{
cout<< "Overloading delete operator " << endl;
free(p);
}
};
int main()
{
student * p = new student("Yash", 24);
p->display();
delete p;
}
OutputOverloading new operator with size: 40
Name:Yash
Age:24
Overloading delete operator
NOTE: In the above new overloaded function, we have allocated dynamic memory through new operator, but it should be global new operator otherwise it will go in recursion
void *p = new student(); // this will go in recursion asnew will be overloaded again and again
void *p = ::new student(); // this is correct
Global overloading of new and delete operator
CPP
// CPP program to demonstrate
// Global overloading of
// new and delete operator
#include<iostream>
#include<stdlib.h>
using namespace std;
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()
{
int n = 5, i;
int * p = new int[n];
for (i = 0; i<n; i++)
p[i]= i;
cout << "Array: ";
for(i = 0; i<n; i++)
cout << p[i] << " ";
cout << endl;
delete [] p;
}
OutputNew operator overloading
Array: 0 1 2 3 4
Delete operator overloading
NOTE: In the code above, in new overloaded function we cannot allocate memory using ::new int[5] as it will go in recursion. We need to allocate memory using malloc only.
Why to overload new and delete?
1. The overloaded new operator function can accept arguments; therefore, a class can have multiple overloaded new operator functions. This gives the programmer more flexibility in customizing memory allocation for objects. For example:
C
void *operator new(size_t size, char c)
{
void *ptr;
ptr = malloc(size);
if (ptr!=NULL)
*ptr = c;
return ptr;
}
main()
{
char *ch = new('#') char;
}
2. NOTE: Code will not only allocate memory for single character but will also initialize the allocated memory with # character.
3. Overloaded new or delete operators also provide Garbage Collection for class's object.
4. Exception handling routine can be added in overloaded new operator function.
5. Sometimes you want operators new and delete to do something customized that the compiler-provided versions don't offer. For example, You might write a custom operator delete that overwrites deallocated memory with zeros in order to increase the security of application data.
6. We can use realloc() function in new function to re-allocate memory dynamically.
7. Overloaded new operator also enables programmers to squeeze some extra performance out of their programs. For example, In a class, to speed up the allocation of new nodes, a list of deleted nodes is maintained so that their memory can be reused when new nodes are allocated.In this case, the overloaded delete operator will add nodes to the list of deleted nodes and the overloaded new operator will allocate memory from this list rather than from the heap to speedup memory allocation. Memory from the heap can be used when the list of deleted nodes is empty.
Similar Reads
Increment (++) and Decrement (--) Operator Overloading in C++
Operator overloading is a feature in object-oriented programming which allows a programmer to redefine a built-in operator to work with user-defined data types. Why Operator Overloading? Let's say we have defined a class Integer for handling operations on integers. We can have functions add(), subtr
4 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning.In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot
8 min read
Different Ways of Operator Overloading in C++
In C++, operator overloading is the concept that allows us to redefine the behavior of the already existing operator for our class. C++ provides a special function called operator function that can be used to achieve operator overloading. In this article, we will learn the different ways in which we
6 min read
C++ Assignment Operator Overloading
Prerequisite: Operator OverloadingThe assignment operator,"=", is the operator used for Assignment. It copies the right value into the left value. Assignment Operators are predefined to operate only on built-in Data types.Assignment operator overloading is binary operator overloading.Overloading ass
4 min read
Types of Operator Overloading in C++
C++ provides a special function to change the current functionality of some operators within its class which is often called as operator overloading. Operator Overloading is the method by which we can change some specific operators' functions to do different tasks.Syntax: Return_Type classname :: op
4 min read
C++ Bitwise Operator Overloading
Prerequisites: Operator OverloadingBitwise Operator in C/C++ In C++, there are a total of six bitwise operators. The six bitwise operators are bitwise AND (&), bitwise OR (|), bitwise XOR (^), left shift (<<), right shift (>>), and bitwise NOT (~). The & (bitwise AND) in C++ take
7 min read
Input/Output Operators Overloading in C++
Operator Overloading is a part of Polymorphism, which enables the feature because of which we can directly use operators with user-defined classes and objects. To read more about this, refer to the article operator overloading in C++. Input/Output Operators(>>/<<) Overloading in C++ We c
2 min read
Overloading stream insertion (<>) operators in C++
In C++, stream insertion operator "<<" is used for output and extraction operator ">>" is used for input. We must know the following things before we start overloading these operators. 1) cout is an object of ostream class and cin is an object of istream class 2) These operators must be
2 min read
deque::operator= and deque::operator[] in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may
4 min read
new and delete Operators in C++ For Dynamic Memory
In C++, when a variable is declared, the compiler automatically reserves memory for it based on its data type. This memory is allocated in the program's stack memory at compilation of the program. Once allocated, it cannot be deleted or changed in size. However, C++ offers manual low-level memory ma
6 min read