That is a really good question. The initialization in C++ is the most complicated topic, so do not hesitate to ask questions. Even experienced developers may misunderstand some concepts.
There are no heap data members or stack data members. All the data members inside the class are allocated one by one close to each other's in the order as they are declared in the class.
What you are missing are the pointers. Pointer is similar to the unsigned int data type. It occupies 4 bytes on the 32-bit platform and 8 bytes on the 64-bit platform regardless of the data size it points to. You may think of memory as an array of bytes and pointer is an index to the array.
In order to construct the object you need a storage. You may think of storage as a region in the memory. What is the size of the object? The answer is sizeof(A). On 64 bit platform sizeof(A) == 16
- 4 bytes for the
int variable
- 4 bytes padding (google it)
- 8 bytes for the pointer to
int
The storage is an addressable memory you can get a pointer:
Platform neutral
- static storage (global variables)
- dynamic storage (heap)
- automatic storage (stack)
- thread local storage
Platform specific
- memory mapped files
- shared memory
- maybe more, depends on platform
So when you construct the object on the stack, the compiler allocates the required amount of memory on the stack and invokes the class constructor.
When you construct the object on the heap using the operator new, the compiler invokes a malloc-like function to allocate some amount of the memory on the heap and then it invokes the class constructor.
In case if object is allocated on the stack, compiler ensures it is destroyed once you return from the function (or leave the scope they say). The same behavior is for the objects allocated on the static storage.
In case if object is allocated on the heap, it is developer's responsibility to destroy the object and release the memory.
In your case you perform two allocations on the heap:
- One is for the
class A object
- Another one is for the
int
Because you never call operator delete the objects you're created are never released. That is a memory leak.
new int(100)creates one singleintvalue, and initializes it to100.new A()all of the object data (its member variables) will be located on the heap. And on a modern 64-bit system a pointer is usually 64 bits, i.e. 8 bytes. Together with theintvariableheight(assuming a size of 4 bytes) and probable padding between the variables (for alignment), the size of your class should be 16 bytes.we have 2 main memories stack and heap.-- This is misunderstanding of the memory concept. The both member variables are located in A storage. One of them points to a heap allocated memory after initialization of A. See Member model