why construction called when i overload the operator new in c++ by calling malloc

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • joey
    New Member
    • Mar 2012
    • 1

    why construction called when i overload the operator new in c++ by calling malloc

    hi:
    i overload the operator new, codes shown as below:

    void * __cdecl operator new(unsigned int size, const char *file, int line)
    {
    void *ptr = (void *)malloc(size);

    return ptr;
    }

    and when i want to create a class object

    CTest::CTest()
    {
    int a = 0;
    }
    CTest::~CTest()
    {
    int b = 0;
    }

    int main()
    {
    CTest* test = new CTest;
    delete test;
    return 0;
    }

    it is very obvious that i overload the operator new by malloc, so when i use the overloaded new operator to create a class object, the CTest's construction should not be called, while the result is complete opposite. And
    my question: why the class's construction function can be called when i create it by malloc but not new?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    When you create an object either using or not using the new operator, the compiler allocates the memory for your onject and then calls the class constructor.

    When you overload operator new, all you are doing is affecting wthe compiler allocates memory for your object. Once that's done, the class constructor is called.

    BTW: Overriding operator new so you can use malloc() is pointless since the default implementation of operator new is to call malloc().

    Comment

    Working...