Reputation: 117
I'm confused about how object allocation is done in the case of inheritance consider the following code.
class Base
{
}
class Derived : Base
{
// some code
}
and from main if we do
Derived d = new Derived();
and
Base b = new Derived();
what is the memory allocation of both cases in the heap. Is the derived object in inside base object or they both are beside each other
Upvotes: 5
Views: 1241
Reputation: 990
In both cases you instanciate objects of the concrete Derived class, so the memory footprint would be the same for both - you refer to them using references of the Base and the Derived class, but you instantiate the Derived class in both cases.
But as to providing a general answer to your question - yes, in memory instances of derived classes contain all the members of their base classes.
Upvotes: 2
Reputation: 28516
Memory allocation for both objects will look exactly the same. Both objects are of the same type Derived
.
Of course, each object will be allocated in its own space on the heap.
What counts when creating objects is the class (type) used to construct the object, not the type of reference where object will be stored.
Each object exists as complete entity, but you can look at it as summary of all parts from all the classes it inherits from. In a way Derived
object instance contains Base
object instance inside. Not the other way around.
Upvotes: 7