ClassA
{
}
ClassB : ClassA
{
}
I can do
ClassA objA = new ClassB();
but why I can't do reverse
ClassB objB = new ClassA();
What exactly happens in back end?How compiler treat this?
ClassA
{
}
ClassB : ClassA
{
}
I can do
ClassA objA = new ClassB();
but why I can't do reverse
ClassB objB = new ClassA();
What exactly happens in back end?How compiler treat this?
Because the compiler automatically casts the deriving class to the base class - it just interprets it as an object of the base class, ignoring other properties. But to cast an object to the derived class, it must have been an object of this derived class before and the compiler wants you to explicitly define the cast. But even if you'd define the cast explicitly, it wouldn't work because the object has never been of the derived type.