Stuck on understanding virtual functions.

So, I sort of understand how virtual functions work and how hiding works.

Virtual functions call the most derived type of that method, and hiding hides the parent class version of the method.

I don't understand why it works that way.

Also, why would you instantiate a object from a derived class and then instantiate another object of the type parent class and assign it the derived object.(i've added a commend the code)

Finally what is the run-time type exactly. As in how does one figure it out?

Sorry for so many questions. I also really appreciate the help!

 using System; class A { public virtual void F() { Console.WriteLine("A.F"); } } class B: A { public override void F() { Console.WriteLine("B.F"); } } class C: B { new public virtual void F() { Console.WriteLine("C.F"); } } class D: C { public override void F() { Console.WriteLine("D.F"); } } class Test { static void Main() { D d = new D(); A a = d; // Why would someone instantiate "a" from "A" and not d? B b = d; C c = d; a.F(); b.F(); c.F(); d.F(); } 

by tarunteam via /r/csharp

Leave a Reply