Advertisement

virtual tables

Started by March 09, 2001 04:02 AM
3 comments, last by Arkon 23 years, 10 months ago
hello how can i call the third virtual function of an instance of a class without knowing the name of the function or simply call the function directly from the virtual table of the class thanks
If you''ve got an instance of a class with virtual functions then all that is really happening is that each virtual function is being overloaded with the address of another function. You know what type of function you want to call so all you need is the pointer to your function.

Given this, you have to type cast the pointer to you function into the correct ''function pointer type'', and then call the function from within the pointer directly using the function call operator ().
Advertisement
can you show me an example please?
i know the theory
but don''t know how to implement it WELL!
This would be a bad, bad, bad thing to do. Why on earth are you thinking of doing this? You should never directly call the virtual function table. Use the virtual functions the way they''re meant to be used, through inheritance.

That being said, this is how you do it:
Each class (or struct) with virtual members has an invisible pointer to a virtual function table. This table is an array of pointers, and is usually static (i.e. there is only one vtable in memory for one kind of object). The location of the vtable pointer is implementation-specific, as are the order of the entries in the table.

The way you would do it is:
- Find out where your implementation stores the vtable pointer, probably either first or last. If it is last, the address for the vtable for object a would be &a + (sizeof a) - sizeof (void*).
- Cast this address to a void** pVTable--pointer to void pointer.
- If you want to call the Nth virtual function, cast your function pointer to that entry: void (*func) () = pVTable[N];
- call func ().

I may have messed up on the details, but that''s the general idea.

Again, no professional would ever do this. I just hope you''re misstating the question and would really like to know some _good_ programming practices.
thanks man

...i know what i ask trust me!
and i just wanna see the code for knowledge
never gonna use this UGLY way!!

This topic is closed to new replies.

Advertisement