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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With