Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inherit operator new from base class

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?

like image 652
zaharpopov Avatar asked Dec 21 '22 19:12

zaharpopov


1 Answers

A new expression will cause an allocation function (operator new) to be called with the correct size for the object being constructed. That's what the size_t parameter for operator new is for.

The particular implementation of operator new in the example, however, can only cope with uniform sized allocation requests. If a derived class didn't override operator new this implementation of operator new would be called with a size that it can't cope with (aka "wrong").

It is, in general, perfectly possible to write an operator new for a class that can handle allocation requests for derived classes.

like image 64
CB Bailey Avatar answered Jan 04 '23 22:01

CB Bailey