When the new operarot is called, the constructor also automatically gets called at the time of returning from new operator.
Likewise, when the delete operarot is called, the destructor also automatically gets called just before calling delete.
The same behaviour can be observed properly if we overload new and delete operator.
The below program shows that constructor gets called after new and destructor is called before delete.
#include "stdlib.h"
#include <iostream>
using namespace std;
class Test
{
int d;
};
void* operator new (size_t sz)
{
cout<<"Inside the global overloaded new
operator..."<<endl;
return malloc(sz);
}
class Sample
{
int data;
public:
Sample();
~Sample();
void* operator new(size_t sz);
void operator delete(void* ptr);
};
Sample::Sample()
{
cout<<"Inside the
constructor.."<<endl;
}
Sample::~Sample()
{
cout<<"Inside the destructor.."<<endl;
}
void* Sample::operator new (size_t sz)
{
cout<<"Inside the overloaded new
operator..."<<endl;
return malloc(sz);
}
void Sample::operator delete(void* ptr)
{
cout<<"Inside the overloaded delete operator..."<<endl;
free (ptr);
}
int main()
{
Sample *s_ptr = new Sample(); //This will call the
overloaded new operator
delete s_ptr;//This will call the overloaded delete operator
Test *t = new Test();
delete t;
}
output:
Inside the overloaded new operator...
Inside the constructor..
Inside the destructor..
Inside the overloaded delete operator...
Inside the global overloaded new operator...
Copyright © Open Sky Technology |