This page (from C++ in action book) shows code:
class Link
{
friend class FreeList;
public:
Link (Link * pNext, int id)
: _pNext (pNext), _id (id) {}
Link * Next () const { return _pNext; }
int Id () const { return _id; }
// allocator
void * operator new (size_t size)
{
assert (size == sizeof (Link));
return _freeList.NewLink ();
}
void operator delete (void * mem)
{
if (mem)
_freeList.Recycle (mem);
}
static void Purge () { _freeList.Purge (); }
private:
static FreeList _freeList;
Link * _pNext;
int _id;
};
And then say
Class Link has a static member
_freeList which is used by the overloaded class-specific operators
new and delete. Notice the assertion
in operator new. It protects us from
somebody calling this particular
operator for a different class. How
could that happen? Operators new and
delete are inherited. If a class
derived from Link didn’t override
these operators, new called for the
derived class would return an object
of the wrong size (base-class size).
Is this saying true? I think new will be called with right size of derived object. Why not?
A
newexpression will cause an allocation function (operator new) to be called with the correct size for the object being constructed. That’s what thesize_tparameter foroperator newis for.The particular implementation of
operator newin the example, however, can only cope with uniform sized allocation requests. If a derived class didn’t overrideoperator newthis implementation ofoperator newwould be called with a size that it can’t cope with (aka “wrong”).It is, in general, perfectly possible to write an
operator newfor a class that can handle allocation requests for derived classes.