using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class basecalss { public void virtual_method() { Console.WriteLine("Virtual in baseclass"); } } class derivedclass1 : basecalss { public void virtual_method() { Console.WriteLine("Override in dervied class1"); } } class implement_override { public static void Main() { 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.
Danatas GerviPosted Aug 23, 2009, 5:18 AM
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.