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.
Answer copied verbatim from what another user, jk, wrote on a exactly same question here on Stackoverflow.
If I tell you I have a dog, you can safely assume that I have a dog.
If I tell you I have a pet, you don't know if that animal is a dog, it could be a cat or maybe even a giraffe. Without knowing some extra information you can't safely assume I have a dog.
similarly a derived object is a base class object (as its a sub class), so can be pointed to by a base class pointer. however a base class object is not a derived class object so can't be assigned to a derived class pointer.
(The creaking you will now hear is the analogy stretching)
Suppose you now want to buy me a gift for my pet.
In the first scenario you know it is a dog, you can buy me a leash, everyone is happy.
In the second scenario I haven't told you what my pet is so if you are going to buy me a gift anyway you need to know information I havent told you (or just guess), you buy me a leash, if it turns out I really did have a dog everyone is happy.
However if I actually had a cat then we now know you made a bad assumption (cast) and have an unhappy cat on a leash (runtime error)
Since BaseClass
is a reference type, obj
is not a BaseClass
object. It is a reference to a BaseClass
object. Specifically, it is a reference to the BaseClass
part of the DerivedClass
.
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