devxlogo

Overload New and Delete in a Class

Overload New and Delete in a Class

It is possible to override the global operators new and delete for a given class. For example, you can use this technique to override the default behavior of operator new in case of a failure. Instead of throwing a std::bad_alloc exception, the class-specific version of new throws a char array:

 #include  //declarations of malloc and free#include #include using namespace std;class C {public:  C();   void* operator new (size_t size); //implicitly declared as a static member function  void operator delete (void *p); //implicitly declared as a static member function};void* C::operator new (size_t  size) throw (const char *){  void * p = malloc(size);  if (p == 0)  throw "allocation failure";  //instead of std::bad_alloc  return p; }void C::operator delete (void *p){	  C* pc = static_cast(p);   free(p);	}int main() {    C *p = new C; // calls C::new   delete p;  // calls C::delete}

Note that the overloaded new and delete implicitly invoke the object’s constructor and destructor, respectively. Remember also to define a matching operator delete when you override operator new.

devx-admin

Share the Post: