Identify correct function pointer from Vtable

We know that function pointer for virtual function are stored in a vtable.When we have multiple function pointer entry in vtable and we call one of the virtual function then how the corresponding or correct function pointer is retrived from Vtable? Who do this stuff? In assembly code i can not see any code or logic to detrmine the correct function pointer.
The index of a function in the vtable is determined from the order the virtual function is declared in the base classes(s) to derived class(s).

Access to vtable will use hardcoded indexes. You won't see any code to calculate this index at runtime.

The type is taken from the method signature in the declaration.

the vtable is generated through the constructor. This is by the way the reason that you can't call virtual functions of an inherited class (from this class) in the constructor
Let me give an example.
1. I have class "Base" and one inherited class from it named "Derived".

2. I have two virtual funtion namely "set()" and "get()".Both are implemented in "Derived" class.So one vtable will be created with two function pointers stored in it.

3. Now i create one instance of "Derived" class, and call derive->set().This call will be resolved through vTable.During runtime appropriate function pointer is retrived from vtable and called.

The question is how it understand that out of two function pointers stored in vtable , which one is for set() function.vTable does not store any function name.If you see the assembly code then vTable index is hardcoded like EDX+ 0 or EDX+4 .

So still not sure who/how picks the function pointer from correct index(in Vtable) for us.
It's the work of the compiler. When it translates the code "derived->set()" it generates the code "call edx". If it sees "derived->get()" - it generates "call edx + 4". The compiler knows which function should be called and where in the VTable is the pointer to this function.
Topic archived. No new replies allowed.