using System;
using System.Collections.Generic;
using System.Text;
namespaceConsoleApplication1
{
classbasecalss
{
publicvoidvirtual_method()
{
Console.WriteLine("Virtual in baseclass");
}
}
classderivedclass1 : basecalss
{
publicvoidvirtual_method()
{
Console.WriteLine("Override in dervied class1");
}
}
classimplement_override
{
publicstaticvoidMain()
{
basecalss baseobj;
derivedclass1 derobj1 = new derivedclass1();
baseobj = derobj1;
baseobj.virtual_method();
Console.ReadLine();
}
}
}
-------------------------------------------------------
Output is: Virtual in baseclass As per the code,
Baseclass object refers child class object, assigned the memory address of Child class.
baseobj.virtual_method(); When we call above, why it calls method of baseclass, although it refers to memory location of child class. Obviously we have not used virtual/override concepts. Point is that if base refers memory address of child, it should not refer its own methods.
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
Danatas GerviRank #4,152 · 361 reputationPosted Aug 23, 2009, 1:18 AM EDT
This is "Hiding".
Check your compiler output – you can find the warning about this.
You may change completely any method in delivered class, but better to use the new
Operator:
new public void virtual_method()
this will say to compiler, that you understand, what are you doing.
In case of hiding – base class cannot know, that its method is hided in child class.
Otherwise, use virtual and overriding.