Operator new overloaded

  • Thread starter Thread starter Alamelu
  • Start date Start date
A

Alamelu

I have overloaded a new operater for a class that returns void * and i have
created an object for that class in heap as below.

CMyClass *pMyClass = new CMyClass(); // Here though i haven't explicitly
casted void* to CMyClass, the compiler doesnt give error at all.

But in c++ for void* to specific type ptr , explicite cast is required. What
was the cause for the above statement to work?

Regards,
Alamelu
 
I have overloaded a new operater for a class that returns void * and i have
created an object for that class in heap as below.

CMyClass *pMyClass = new CMyClass(); // Here though i haven't explicitly
casted void* to CMyClass, the compiler doesnt give error at all.

But in c++ for void* to specific type ptr , explicite cast is required. What
was the cause for the above statement to work?

You are confusing the function named "operator new" with the operator named
"new", the latter being what you used in "new CMyClass". The function does
return void*, and the operator calls it to allocate memory. Basically, the
operator does this:

// Allocate memory for an X.
void* p = operator new(sizeof(X));
// Use placement new to construct an X in the memory pointed to by p.
new (p) X;
// Now return a pointer to the dynamically allocated X.
return (X*) p;

That's all legal code, BTW.

P.S. This is not C#, and the parens aren't required when you say "new X()".
Normally, they should be omitted. There is actually a difference between
new X and new X() when (loosely speaking) X is a type with no ctors. The
latter will zero-initialize the object, while the former will leave it
uninitialized.
 
Back
Top