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.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist