Hello,
I have a question on inheritance, please see the code below for reference:
****************************************************************
using System;
public class Parent
{
internal int id;
public Parent(int id)
{
this.id = id;
}
public void Meth( )
{
Console.WriteLine("Hello from Parent.Meth, id={0}", id);
}
}
public class Child : Parent
{
public Child(int id) : base(id) // call base constructor
{
}
public new void Meth( )
{
Console.WriteLine("Hello from Child.Meth, id={0}", id);
}
}
public class Executer
{
public static void Main( )
{
Parent p = new Parent(1); p.Meth();
Child c = new Child(2); c.Meth();
Parent pp = new Parent(3); pp.Meth();
Parent cc = new Child(4); cc.Meth();
}
}
****************************************************************
the cc.Meth() call returns "Hello from Parent.Meth, id=4", that is, the
parent method is called, though variable cc was assigned Child object. I
realize, that if I'd mark Meth virtual in Parent class, and mark child Meth
with override, I'd get "Hello from Parent.Meth, id=4" instead. But, in the
first case, where did the Child.Meth get? Is is no more accessible due to
type conversion that happened because variable cc is marked as type Parent?
I have hard time understanding why I'd have to use "virtual" and "override",
if I can simply leave the parent class method as is, and define child method
using "new", and I only have to assign child object instances to child type
variables (vs parent type).
Thanks,
Pavils