S
Siemel Naran
pembed2003 said:possible function definition. The lookup (not sure how the actual
virtual table is implemented but if it's something like a binary tree
or hash table then...) thus takes appr. the same amount of time.
I think the virtual table is implemented as an array of pointers to
function. It works well whenever a pointer to a function of any signature
has the same size, which is normally the case. If you have a class as
follows.
Note what follows is a typical implementation, not what the standard
mandates.
class Foo {
virtual ~Foo();
virtual int f(int, int);
virtual double g(int) const;
};
then the virtual table is an array of length 3. Each element in the array
is a function pointer, but each function pointer is a different signature!
Sure, the compiler can do that, but we can't!
Thus, there are 3 C style functions.
void __Foo_destructor(Foo *);
int __Foo_f(Foo *, int, int);
double __Foo_g(const Foo *, int);
and the virtual table is
typedef void (* __FunctionPtr)(); // pointer to non-member function
typedef __FunctionPtr[3] __Foo_vtable_type; // typedef for array of 3
function pointers
__Foo_vtable_type __Foo_vtable = {
(__FunctionPtr)(&Foo_destructor),
(__FunctionPtr)(&Foo_f),
(__FunctionPtr)(&Foo_g)
};
When you say foo->g(3) the compiler knows you mean the element
__Foo_vtable[2] and that it's real signature is double (*)(const Foo *,
int). Thus the call translates to
{
typedef double (* _Foo_vtable2)(const Foo *, int);
const __Foo_vtable_type& __vtable = foo->__vpointer;
_Foo_vtable2 __tmp = (_Foo_vtable2)(__vtable[2]);
(*__tmp)(foo, 3);
}