Alex Rivera | Logout

size_t parameter new operator

Asked 2013-05-19T22:50:18.520
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.

Edit
Report

1 Answer

0

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

answered 2013-05-19T22:52:13.167

Your Answer