11

I have a point in my mind which I can't figure out about new operator overloading. Suppose that, I have a class MyClass yet MyClass.h MyClass.cpp and main.cpp files are like;

//MyClass.h

class MyClass {
   public:
     //Some member functions
     void* operator new (size_t size);
     void operator delete (void* ptr);
     //...
};

//MyClass.cpp

void* MyClass::operator new(size_t size) {
   return malloc(size);
}

void MyClass::operator delete(void* ptr) {
   free(ptr);
}

//main.cpp

//Include files
//...

int main() {
   MyClass* cPtr = new MyClass();
   delete cPtr
} 

respectively. This program is running just fine. However, the thing I can't manage to understand is, how come new operator can be called without any parameter while in its definition it has a function parameter like "size_t size". Is there a point that I am missing here? Thanks.

mecid
  • 407
  • 4
  • 12

3 Answers3

9

Don't confuse the "new expression" with the "operator new" allocation function. The former causes the latter. When you say T * p = new T;, then this calls the allocation function first to obtain memory and then constructs the object in that memory. The process is loosely equivalent to the following:

void * addr = T::operator new(sizeof(T));    //  rough equivalent of what
T * p = ::new (addr) T;                      //  "T * p = new T;" means.

(Plus an exception handler in the event that the constructor throws; the memory will be deallocated in that case.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

The new-expression new MyClass() is basically defined in two steps. First it calls the allocator function, which you have overloaded, to get some allocated memory. It passes the size of the type MyClass to that allocator function, which is why the size_t argument is required. After this, it constructs an object in that allocated memory and returns a pointer to it.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
0

The compiler knows the size of your class. Basically, it's passing sizeof(MyClass) into your new function.

paddy
  • 60,864
  • 6
  • 61
  • 103