views:

386

answers:

5

Hi if I am creating something on the stack using new I declare it like:

object *myObject = new object(contr, params);

Is there a way to declare this such as:

object *myObject;
myObject = new object(constr, params);

Is this correct?

+10  A: 

Yes, that is correct. But new does not create things on the stack, it creates them on the heap.

To create object on the stack you would do:

object myObject(constr, params);

There is no other way to create an object on the stack and once it is created on the stack you can't "recreate" it with the same name later in the same function.

SoapBox
"There is no other way to create an object on the stack" - not strictly true, but for the purposes of a beginner, it's certainly the only sensible way :-)
Steve Jessop
Correction: You CAN recreate it in the same function, as long as it's in a different scope. ( void fun() { {int a;} {int a;} } )
Marcin
+2  A: 

Yes that is correct but it won't allocate on the stack. Instead it will allocate on the heap. If you want to allocate on the stack, declare it this way

object myObject(contr,params);
JaredPar
+1  A: 

If you want the object to be on the stack, you need to say

object myObject(contr, params);
Mr Fooz
+3  A: 

As others have said, new will create *myObject on the heap. For completeness I'll point out that the pointer to the object, called myObject (note there is no *) does reside on the stack the way you declared it. Since stack variables go out of scope when you leave a function, you must delete the object before returning, or transfer the pointer to another variable with a longer lifetime. Neglecting to delete a heap object whose pointer is in a stack variable before returning from a function is sort of the canonical memory leak scenario (though far from the only one)

Steve Fallows
A: 

This code:

object *myObject;
myObject = new object(constr, params);

...is legal & correct. But please please initialize myObject to something when you allocate it. Remember 'myObject' is itself not an instance of the 'object', but an instance of a pointer to an 'object'. So when you declare this pointer like this:

object *myObject;

...you are leaving it uninitialized. Instead, do this:

object *myObject = 0;
myObject = new object(constr, params);

...and when you delete it:

delete myObject;
myObject = 0;

People may debate that you should set it to NULL rather than 0, but both are fine as far as the language is concerned and this is mostly a matter of style and what your coworkers are used to.

John Dibling