www.digitalmars.com         C & C++   DMDScript  

c++ - Opeator new

reply MR <web rnetf.com> writes:
I have been trying to overload operator new with strange results.
Below is the code:

The output, when running the example is:

dmTest: ta1
--------------------> A(size_t, int)
<-------------------- A(size_t, int)
--------------------> A()
<-------------------- A()
iVal: -1

I don't understand why a default constructor is being called AFTER the new
constructor; it wipes out all initialization. Have I done something wrong
or is the compiler invoking constructors in the wrong order?

Regards -

CODE
====================================================================================
#include <stdlib.h>
#include <stdio.h>

class A
{
public:
   A();
   A(int);
   ~A();
   void* operator new(size_t, int val);

   void print();

public:
   int   iVal;
};


// --------------------------------------------------
A::A()
{
printf("--------------------> A()\n");
   iVal = -1;
printf("<-------------------- A()\n");
}

// --------------------------------------------------
A::~A()
{
   iVal = -1;
}

// --------------------------------------------------
void* A::operator new(size_t t, int val)
{
printf("--------------------> A(size_t, int)\n");
   A* newA = (A*)malloc(sizeof(A));
   newA->iVal = val;
printf("<-------------------- A(size_t, int)\n");
   return newA;
}

// --------------------------------------------------
void A::print()
{
   printf("iVal: %i\n", iVal);
}


// ===================================================
int main()
{
   A* aPtr;

   aPtr = new(7) A;
   aPtr->print();
}
May 05 2009
parent Bertel Brander <bertel post4.tele.dk> writes:
MR skrev:
 I have been trying to overload operator new with strange results.
 Below is the code:
 
 The output, when running the example is:
 
 dmTest: ta1
 --------------------> A(size_t, int)
 <-------------------- A(size_t, int)
 --------------------> A()
 <-------------------- A()
 iVal: -1
 
 I don't understand why a default constructor is being called AFTER the new
 constructor; it wipes out all initialization. Have I done something wrong
 or is the compiler invoking constructors in the wrong order?

new is not a "constructor", new merely allocates room for the object. After room has been allocated, by your new operator or the default one, the appropriate constructor is called.
May 05 2009