I have the following code in C #:
namespace ConsoleApplication4
{
public class BaseClass
{
public BaseClass()
{
System.Console.WriteLine("BaseClass::BaseClass();");
}
}
public class DerivedClass : BaseClass
{
public int num;
public DerivedClass(int x)
{
num = x;
System.Console.WriteLine("DerivedClass::DerivedClass(int x);");
}
}
class Program
{
static void Main()
{
BaseClass A = new DerivedClass(20);
//B.num = 20; Erro
//Mas se converter para DerivedClass e mostrar resultado do 'num':
DerivedClass B = (DerivedClass)A;
System.Console.WriteLine(B.num); //Ele mostra o resultado que modificou no construtor! Ué? Por que isso pode?
/* Resultado:
* BaseClass::BaseClass();
* DerivedClass::DerivedClass(int x);
* 20
*/
System.Console.ReadKey();
}
}
}
The comments in the code are already self-explanatory.