Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory allocation for object in inheritance in C#

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

like image 830
sandeep addala Avatar asked Mar 07 '23 05:03

sandeep addala


1 Answers

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.

like image 128
Dalija Prasnikar Avatar answered Mar 19 '23 05:03

Dalija Prasnikar