• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

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

Carlis

Senior member
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
 
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).
 
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.
 
Back
Top