1

I have class BaseObject and InheritedObject inherites from BaseObject.

In BaseObject, I have field "public int Id". In InheritedObject, I have field "public new long Id".

Question: When new instance of InheritedObject is created, are inherited object and base object stored in 2 memory space/block?

For more specific, I have address 0x001 to store the BaseObject and address 0x100 to store the InheritedObject . And InheritedObject has reference to BaseObject using address 0x001.

Vu Nguyen
  • 3,605
  • 3
  • 22
  • 34
  • If you're asking whether the object and its subobjects are stored together, then yes - an object has all inherited subobjects stored within itself. They don't hold pointers or references to each other. If you're asking something else you'll need to clarify further. – molbdnilo May 07 '14 at 10:53
  • @molbdnilo: my concern is do we have 2 memory spaces for each object? They can be next to each other, or the InheritedObject includes the BaseObject memory space? – Vu Nguyen May 08 '14 at 01:25

1 Answers1

2

Assuming c#, Yes two discrete fields are created. So two memory space will be allocated.

When you add new modifier, you shadow the base class's field. So when you access the field with derived type you'll get the value from InheritedObject and to get the value of BaseObject.Id you can access it via base object type.

Note: You can change the data type also when shadowing in derived class, so it is obvious that separate memory location is used.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • If I dont use new modifier (e.g. I use override modifier), do I have 2 memory space for 2 Ids? My concern is do we have 2 memory spaces for each object? They can be next to each other, or the InheritedObject includes the BaseObject memory space? – Vu Nguyen May 08 '14 at 01:26
  • @VuNguyen You can't use override modifier for field. – Sriram Sakthivel May 08 '14 at 03:23
  • Sorry, I meant if I use properties, like this public override int Id {get; set; } – Vu Nguyen May 08 '14 at 08:11
  • 1
    @VuNguyen Yes, if you use like that base class will have a separate backing field and derived class will also have a separate backing field. Hence two memory locations will be allocated. – Sriram Sakthivel May 08 '14 at 08:16
  • Thanks so much for you help. I have an argument with my friend and he don't know this, he insist that if I do overriding or hiding, no matter what, there is only one memory space, but I don't know how to show him. Do you have any official documentation somewhere? – Vu Nguyen May 08 '14 at 09:35
  • 1
    Download IL Spy, or reflector and check the decompiled compiled code? If not [this should answer your friend's question](http://stackoverflow.com/questions/6417463/are-anonymous-backing-fields-still-created-for-virtual-auto-implemented-properti) – Sriram Sakthivel May 08 '14 at 09:38