I ran across this post today when I was cruising around the awesomness that is the internet:
http://blogs.msdn.com/rakkimk/archive/2007/05/11/virtual-functions-explored-c-c-examples.aspx
While Rakki did an excellent job of explaining C++ virtual table construction and invocation, I believe C# developers would really like a little more “beef” on their side of the fence. Therefore, I will do a little comparison between the two. The differences are huge!
In C++, you cannot call a derived class virtual method from a base class constructor because the derived class virtual table hasn’t been created yet. In C#, you absolutely can. That is a major difference!
For example, take this code in C++:
class Base
{
public:
// All virtual method calls in constructors are static; not dynamic.
Base () { Foo(); }
virtual void Foo() { cout << "Base::Foo" << endl; }
};
class Derived : public Base
{
public:
Derived () { Foo(); // Calls Derived::Foo }
virtual void Foo() { cout << "Derived::Foo" << endl; }
};
int main ()
{
Derived derived;
}
This displays:
Base::Foo
Derived::Foo
Now, take the same code in C#:
public class Base
{
public Base () { Foo(); }
public virtual void Foo() { Console.WriteLine("Base::Foo"); }
}
public class Derived : Base
{
public Derived () { Foo(); }
public override void Foo() { Console.WriteLine("Derived::Foo"); }
}
class Program
{
static void Main() { new Derived(); }
}
This displays:
Derived::Foo
Derived::Foo
Why? Because in C#, the virtual table has already been setup. So when the base class constructors get called, the virtual method invocation inside the constructor is truly virtual and the actual derived class instance being created is invoked (dynamically). If this is not the behaviour you want, you need to use ‘new virtual’ on each derived class instead of ‘override’. If you do that, you will get the same behaviour as in C++.
Enjoy!










