class Widget
{
public:
Widget() {
cout<<"~Widget()"<<endl;
}
~Widget() {
cout<<"~Widget()"<<endl;
}
void* operator new(size_t sz) throw(bad_alloc) {
cout<<"operator new"<<endl;
throw bad_alloc();
}
void operator delete(void *v) {
cout<<"operator delete"<<endl;
}
};
int main()
{
Widget* w = 0;
try {
w = new Widget();
}
catch(bad_alloc) {
cout<<"Out of Memory"<<endl;
}
delete w;
getch();
return 1;
}
In this code, delete w
does not call the overloaded delete
operator when the destructor is there. If the destructor is omitted, the overloaded delete
is called. Why is this so?
Output when ~Widget() is written
operator new
Out of Memory
Output when ~Widget() is not written
operator new
Out of Memory
operator delete