The trick is that you can use a reference to the base class to reference an inherited one and, at runtime, when you call a virtual function using that reference, the overridden one in the inherited class is called. Consider the code below:
class BaseClass
{
public virtual void Test()
{
Console.WriteLine("BaseClass:Test()");
}
}
class ChildClassA : BaseClass
{
public override void Test()
{
Console.WriteLine("ChildClassA:Test()");
}
}
class ChildClassB : BaseClass
{
public override void Test()
{
Console.WriteLine("ChildClassB:Test()");
}
}
Now suppose that you write something like this:
BaseClass obj = new ChildClassA();
obj.Test();
obj = ChildClassB();
obj.Test()
The output that you get is something like this:
ChildClassA:Test()
ChildClassB:Test()