简体   繁体   中英

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

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.

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 cades.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM