Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual method tables

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

like image 452
GurdeepS Avatar asked Mar 09 '10 23:03

GurdeepS


People also ask

What is a virtual method table in C++?

V-tables (or virtual tables) are how most C++ implementations do polymorphism. For each concrete implementation of a class, there is a table of function pointers to all the virtual methods. A pointer to this table (called the virtual table) exists as a data member in all the objects.

Which are virtual tables?

A virtual table is an object that presents an SQL table interface but which is not stored in the database file, at least not directly. The virtual table mechanism is a feature of SQLite that allows SQLite to access and manipulate resources other than bits in the database file using the powerful SQL query language.

How do virtual tables work?

A virtual table contains one entry for each virtual function that can be called by objects of the class. Each entry in this table is simply a function pointer that points to the most-derived function accessible by that class.

What are virtual tables in Java?

A vtable is simply an array of function pointers. The slots in the array correspond to the methods of of a class. Since methods are fixed per class, we do not have to maintain an array of functions for each object. Rather, it suffices to declare one vtable array per class.


2 Answers

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.

like image 189
Guffa Avatar answered Oct 06 '22 00:10

Guffa


The C# virtual function table works basically the same as the C++ one, so any resources which describe how the C++ virtual function table works should help you pretty well with the C# one as well.

For example, Wikipedia's description is not bad.

like image 25
Dean Harding Avatar answered Oct 06 '22 00:10

Dean Harding