Archive for July, 2007

Overloading new, delete in C++

Saturday, July 7th, 2007

environment C++ with Visual Studio 2005

problem Override new operator including additional parameter. Override delete operator and check if the correct delete operator is called when invoked on a base class.

solution


class A
{
};

class B : public A
{
public:
void *operator new( size_t stAllocateBlock, char chInit )
{
printf("B.new called\n");
return malloc(stAllocateBlock);
}

void operator delete( void * p, size_t)
{
printf("B.delete called\n");
free(p);
}
};

main:

A* a = new('a') B;

delete a;

Well, B::delete is not invoked.

links