As a class is instantiated on the heap. Are all member vars then also allocated on the heap, or somewhere else. Is there then any good in allocating member vars explicit on
the new
ed object is treated as a contiguous allocation. creating a new instance of abc
creates an allocation with a minimum size of sizeof(abc)
.
the system does not allocate members of the class separately when you create via new
. to illustrate: new
does not call new
for each member, sub-member. therefore, the data members are stored in the contiguous allocation created by new
, which is a single allocation.
in the case of the vector
, the vector internally uses dynamic allocation for its elements -- this is accomplished using a separate allocation. this allocation is made within vector's implementation.
therefore the members do reside on the heap, but they exist as part of the abc
instance and that instance uses one allocation, excluding any allocations the data members create.
Is there then any good in allocating member vars explicit on the heap?
yes. there are many reasons you might choose to do this. considering the context of the question: you should favor declaring your members as values until there is a very good reason not to (details here). when you need to declare your member as a heap allocation, always use an appropriate container (e.g. auto pointer, shared pointer) because this will save you tons of effort, time, and complexity.