Saturday, March 14, 2009

Virtual method call at runtime

The virtual mechanism (as you

correctly depicted as being implemented through a V-table) ensures

that the virtual method will be called no matter the type of the

reference you're using to call the method. Consider this example:


class A
{
public void M()
{
Console.WriteLine("A.M() being called");
}

public virtual void N()
{
Console.WriteLine("A.N() being called");
}
}

class B : A
{
public new void M()
{
Console.WriteLine("B.M() being called");
}

public override void N()
{
Console.WriteLine("B.N() being called");
}
}


say

A a = new B();

a.M();
a.N();


The results would be

A.M() being called
B.N() being called

because M() is called based on the compile time type (I am declaring

a as being an A) and N() is called based on the runtime type (after

all a is a B). Virtual introduces an method call indirection by

using a pointer to the method instead of the method itself. Because

of that the call is slower. C#, like C++ chose to be flexible in

this area, introducing the virtual keyword and retain the best of

both worlds (speed vs polymorhism) whereas, for instance Java,

considers all instance methods as virtual.

No comments: