operator overloading

 
 

Question

How to overload NEW operator in C++?

The C++ code below has a

The C++ code below has a base class and a derived class base_one. The base class has an overloaded version of new, which takes two arguments: the number of bytes to allocate and a pointer to a memory pool allocation object. The compiler automatically plugs in the type size (the first argument to the overloaded new). The call to new then takes the form
pClass = new( user args ) type
which is expanded into a call to the overloaded new function
void *operator new( type size, user args );
class base {
public:
base() { }
void *operator new( unsigned int num_bytes, pool *mem)
{
return mem->GetMem( num_bytes);
}
virtual void pr(void) = 0;
};
class base_one : public base {
private:
int a;
public:
base_one() {}
void pr(void)
{
// local print
}
};
main()
{
base *pB1;
pool mem;
pB1 = new( &mem ) base_one;
pB1->pr();
}
In this example there is a memory allocation type pool. This is passed as an argument to new, which uses the GetMem class function to allocate memory.