Jes
Jes

Reputation: 2694

Size information when overloading C++ new operator

The C++ memory allocation operator has the form of operator new (size_t s). When I overload the new operator for a class object of type T, does it guarantee the input argument (i.e., size_t s) of the operator new is exactly sizeof(T)? If yes, why does this function still need the size as input argument?

Upvotes: 12

Views: 857

Answers (1)

R Sahu
R Sahu

Reputation: 206667

It is possible to override operator new in a base class and use it to allocate objects of derived class type.

struct Base
{
    void* operator new (size_t s) { ... }
    int a;
};

struct Derived : public Base
{
   int b;
};

Derived* d = new Derived; 

When allocating memory for Derived, Base::operator new(size_t) will be used. The value of the argument will be sizeof(Derived). Without that argument, the compiler cannot allocate the right amount of memory for an object of type Derived.

Upvotes: 14

Related Questions