Virtual method tables

GurdeepS picture GurdeepS · Mar 10, 2010 · Viewed 20.1k times · Source

When discussing sealed classes, the term "virtual function table" is mentioned quite frequently. What exactly is this? I read about a method table a while ago (I don't remember the purpose of the purpose of this either) and a google/search on here brings up C++ related results.

Thanks

Answer

Guffa picture Guffa · Mar 10, 2010

The "virtual function table" or "virtual method table" is a list of method pointers that each class has. It contains pointers to the virtual methods in the class.

Each instance of a class has a pointer to the table, which is used when you call a virtual method from the instance. This is because a call to a virtual method should call the method associated with the class of the actual object, not the class of the reference to the object.

If you for example have an object reference to a string:

object obj = "asdf";

and call the virtual method ToString:

string text = obj.ToString();

it will use the String.ToString method, not the Object.ToString method. It's using the virtual method table of the String class (which the pointer in the string instance is pointing to), not the virtual method table of the Object class.