I have been a .Net coder (can not say I am a programmer) for 2 years. There is one question that I can not understand for years, that is how could an instance of the base class hold an instance of the derived class?
Suppose we have two classes:
class BaseClass
{
public A propertyA;
public B propertyB;
}
class DerivedClass :BaseClass
{
public C propertyC;
}
How could this happen:
BaseClass obj = new DerivedClass ()
I mean, the memory model of BaseClass
, has no space for the newly added propertyC, so how could it still hold the value of propertyC?
On the other side, how could this can not happen:
DerivedClass obj = new BaseClass()
I thought this is the correct way since the memory model of DerivedClass
has all the spaces for the BaseClass and even more. But this is not true, why?
I know I am asking a really stupid question, but could someone give me a more detail answer of this? It would be better from the perspective of the memory or compiler.