Overloading New And Delete Operator In C++
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.
Syntax for overloading the new operator :
void*
operator new(size_t size);
Syntax for overloading the delete
operator :
void
operator delete(void*);
Fig:Overloading New And Delete Operator In C++
Program:
#include<iostream>
#include<stdlib.h>
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 = ::new student();
return p;
}
void operator delete(void * p)
{
cout<< "Overloading delete operator
" << endl;
free(p);
}
};
int main()
{
student * p = new student("Pramod", 22);
p->display();
delete p;
}
Output:
Overloading new
operator with size:16
Constructor is called
Name:Pramod
Age:21
Overloading delete
operator
No comments:
Post a Comment