C++: Declaring and initiating object. When does the system reserve memory?

Carlis

Senior member
May 19, 2006
237
0
76
Hi

I want to know at which step memory is reserved for my object.
I do:

myObject *O; (1)

O=new myObject(args); (2)


Does it cost memory to declare (1) object without implementing it (2)

Regards
Carlis
 

Cogman

Lifer
Sep 19, 2000
10,286
145
106
You haven't declared an object at stage 1, you have declared an object pointer. The memory cost is that of a pointer (Somewhere around 4 bytes in a 32bit program). At 2, is when the memory for the object is created on the heap, after the memory is created, the object runs through its constructor (using the new command).
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
Cogman's answer is a good one. If you're thinking clearly about what's going on, then each of these things you're creating is an object. The first thing that gets created is a scalar value that holds an address, i.e. a pointer. We can't tell from your example where it gets created, but it is probably a local variable inside a function and lives on the stack. You then assign the return value of the new operator to that pointer. The new operator allocates memory on the heap for your class instance, and causes its constructor to execute, then returns the address of the allocated memory.