Listing 23 A class with its own versions of new and delete

// t.h
#include <iostream.h>

class T
{
   int x;
public:
   T();
   T(int);
   ~T();

   // Override both scalar and array verions
   void *operator new(size_t);
   void operator delete(void *, size_t);
   void *operator new[](size_t);
   void operator delete[](void *);
};

inline T::T() : x(0)
{
   cout << "T::T()" << endl;
}

inline T::T(int i) : x(i)
{
   cout << "T::T(int)" << endl;
}

inline T::~T()
{
   cout << "T::~T()" << endl;
}

inline void *T::operator new(size_t siz)
{
   cout << "T::new (allocating " << siz << " bytes)" << endl;
   return ::operator new(siz);
}

inline void T::operator delete(void *p, size_t siz)
{
   cout << "T::delete (" << siz << " bytes)" << endl;
   if (p)
      ::operator delete(p);
}

inline void *T::operator new[](size_t siz)
{
   cout << "T::new[] (allocating" << siz << " bytes)" << endl;
   return ::operator new(siz);
}

inline void T::operator delete[](void *p, size_t siz)
{
   cout << "T::delete[]" << endl;
   if (p)
      ::operator delete(p);
}

class U : public T
{
   int y;
public:
   U();
   U(int);
   ~U();
};

inline U::U() : T(0), y(0)
{
   cout << "U::U()" << endl;
}

inline U::U(int i) : T(i), y(i)
{
   cout << "U::U(int)" << endl;
}

inline U::~U()
{
   cout << "U::~U()" << endl;
}

/* End of File */