Operator new overloaded

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?Utf-8?B?QWxhbWVsdQ==?=

    Operator new overloaded

    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


  • Doug Harrison [MVP]

    #2
    Re: Operator new overloaded

    On Tue, 23 Sep 2008 11:38:10 -0700, Alamelu
    <Alamelu@discus sions.microsoft .comwrote:
    >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.

    --
    Doug Harrison
    Visual C++ MVP

    Comment

    Working...