Tuesday 5 March 2019

iTables and vTables

It's beautiful to see a mistery unveil before you many years after the first time you tried to disclose it. It suddenly brings you so many memories of the person you were at that time... OK, to the point. It's been more than 15 years since I learnt that the dispatch of virtual methods in languages like C++, Java or C# worked thanks to a memory structure called vTable (Virtual Methods Table). Long in short, the vTable holds function pointers, and the caller knows the index for each method in the table. In a derived class, each method present in the parent class occupies the same position (index) in the child vTable that in the parent vTable, pointing to the new implementation (if the method has been overriden) or tothe same implementation of the father.

That's clear and simple for single inheritance hierarchies, but it's not enough for multiple inheritance (either of classes or interfaces). If we are implementing 2 interfaces, each of them will have a method that should be in position 1 of the table, so what? 15 years ago I could not find a clear explanation of how this issue was solved. I could imagine that there would be additional tables and somehow the code would use one or another structure... but as I've said, I could not find a clear explanation.

Don't ask me how, but for some reason the other day I came across an amazing article providing an excellent explanation. The description of Java's implementation is particularly clear. So in a class implementing 2 interfaces we still have a vTable, and we also have one iTable for each interface. For Interface1.MethodA we'll have and entry for MethodA in iTable1 and another one in the vTable, that obviously hold the same memory address pointing to the corresponding MethodA implementation. Same for Interface2.MethodB (with the entry in iTable2). The big question is how does the runtime select iTable1 or iTable2? Well, each interface has an ID, and the iTables placed in a sort of dictionary using the ID as key. The code invoking the method through the interface uses the interface ID to locate the corresponding iTable. Simple and Brilliant. Just check the aforementioned article to really get it.

No comments:

Post a Comment