Note: This question is purely about asm.js
not about C++ nor any other programming language.
As the title already says:
How should a fu
I am not very familiar with the exact syntax of asm.js, but here is how I implemented a vtable in a compiler of mine (for x86):
Each object are derived from a struct like this:
struct Object {
VTable *vtable;
};
Then the other types I use will look something like this in c++-syntax:
struct MyInt : Vtable {
int value;
};
which is (in this case) equivalent to:
struct MyInt {
VTable *vtable;
int value;
};
So the final layout of the objects are that at offset 0, I know I have a pointer to a vtable. The vtable I use is simply an array of function pointers, again in C-syntax the type VTable could be defined as follows:
typedef Function *VTable;
Where in C i would use void * instead of Function *, since the actual types of the function will vary. What is left for the compiler to do is:
1: For each type containing virtual functions, create a global vtable and populate it with function pointers to the overridden functions.
2: When an object is created, set the vtable member of the object (at offset 0) to point to the global vtable.
Then when you want to call virtual functions you can do something like this:
(*myObject->vtable[1])(1);
to call the function your compiler has assigned the ID 1 in the vtable (methodB in the example below).
A final example: Let's say we have the following two classes:
class A {
public:
virtual int methodA(int) { ... }
virtual int methodB(int) { ... }
virtual int methodC(int) { ... }
};
class B : public A {
public:
virtual int methodA(int) { ... }
virtual int methodB(int) { ... }
};
The VTable for class A and B can look like this:
A: B:
0: &A::methodA 0: &B::methodA
1: &A::methodB 1: &B::methodB
2: &A::methodC 2: &A::methodC
By using this logic, we know that when we are calling methodB on any type derived from A, we shall call whatever function is located at index 1 in the vtable of that object.
Of course, this solution do not work right away if you want to allow for multiple inheritance, but I am fairly sure it can be extended to do so. After some debugging with Visual Studio 2008, it seems like this is more or less how the vtables are implemented there (of course there it is extended to handle multiple inheritance, I have not tried to figure that out yet).
I hope you get some ideas that can be applied in asm.js at least. Like I said, I do not know exactly how asm.js works, but I have managed to implement this system in x86 assembly and I do not see any issues with implementing it in JavaScript either, so I hope it can be used in asm.js as well.