C++ Memory Usage – Declaring Members on the Heap for Heap Objects

cmemory usage

I recently reviewed some C++ code written by a fellow student, and he did something I wouldn't think is necessary. In main(), he creates a class object on the heap with the new operator. Then he calls a method of the object, which itself calls the new operator to create a large vector.

My gut tells me this is unnecessary–since the class object was allocated to the heap, its member objects should also be on the heap, making the use of new superfluous. Am I right?

Best Answer

Unless I understood something wrong, no, what he did is correct. The fact that an object is on the heap or the stack has nothing to do to where the reference belongs: you could have, for example, heap objects referencing stack ones and vice versa.

If he did not use the new operator to instantiate his second object on the first one's method, the object would have been cleaned at method return like any other stack object.

Example : you have a B* b field on your object A. In your constructor, you do

{
    B tmpB = B()
    this->b = *tmpB
}

As soon as the constructor leaves, your b field points to memory that is no longer a valid B object.

However, if you have a B b field, that is different. Here b holds a value and no longer a reference. Hence, it will be on the same place A is (stack if A is on stack or heap if A is allocated via new).