views:

64

answers:

2

If I have:

struct Base
{
};

struct Derived : Base
{
};

And I create Derived in main:

Derived* d = new Derived;

where (on heap or on stack) is my base created? Am I reasoning correctly that a Base is a part of a Derived so it is created wherever Derived is created? Or does it work in some other way?

+5  A: 

The base class contribution is generally part of the derived object (and so uses part of the object's memory along with the derived portion). Your example can make this irrelevant, however, because the base class portion takes up zero memory due to the C++ empty base class optimization.

Despite the fact that the derived struct is empty as well, the final object must be at least one byte in size, because all objects must take up space, to ensure that the addresses of two different objects will be different. See: Why is the size of an empty class not zero? for more info.

Michael Goldshteyn
+2  A: 

The Base is created in the same memory segment as the Derived. In your example, since you allocate Derived on the heap, the Base is also allocated on the heap. They form one contiguous object in memory.

Charles Salvia