TITLE: Class-specific new handlers (This example is loosely based upon "Effective C++" by Scott Meyers, p. 21-24. The code is taken verbatim; the commentary is not.) Suppose that as a class designer, you would like a behaviour such that failure to allocate memory could be handled differently for each kind of class. class X { public: static void outOfMemory (); ... }; class Y { public: static void outOfMemory (); ... }; main () { X* p1 = new X; // if unsuccessful call X::outOfMemory Y* p1 = new Y; // if unsuccessful call Y::outOfMemory } This can be accomplished by using the C++ standard "set_new_handler" function. This function takes a function pointer (which is called when a memory allocation fails) and returns a function pointer to the current handler. In this example, a class X provides an operator "new" which temporarily installs its own handler, uses the global allocator, then restores the original handler. The details of the implementation are shown below. typedef void (*PEHF) (); class X { private: static PEHF currentPEHF; public: static PEHF set_new_handler (PEHF p); void* operator new (size_t size); }; void* X :: operator new (size_t size) { PEHF currentHandler = ::set_new_handler (currentPEHF); void* memory = ::new char [size]; ::set_new_handler (currentHandler); return memory; }