Can any one please let me know whether the virtual table and virtual pointer is per class or per object? If they are per object, why can't they be shared between the objects of same class instead of maintaining a copy per object?
It is implementation defined, but it is typically a static vtable per class, and each instance has a vptr to the vtable for the class. The reason each instance needs the pointer is because the compiler may not know at compile time which concrete implementation a particular variable is going to be, so a pointer to the relevant vtable has to be deterministically accessible from the reference. Hence the whole point of having a vtable :)
Yes exactly. A virtual table is per class, it would make no sense otherwise. A virtual pointer is nothing. Don't use this term!
Virtual Pointer
Just throw away your C++ and think how it would be implemented in C:
typedef VirtualFunctionsOfAClass AClassesVTable
struct AClass {
some_data
AClassesVTable *vptr;
};
struct VirtualFunctionsOfAClass {
int(*someFunc1)(struct AClass* _This, int a);
int(*anotherFunc1)(struct AClass* _This, int a);
};
static AClassesVTable vtableOfClassA = {func1, func2};
struct AClass* constructAClass() {
AClass* ac=malloc(sizeof(AClass));
ac->vptr = &vtableOfClassA;
return ac;
}
void aNonVirtualMemberFunctionOfClassA(AClass* _This, more arguments)
{
return; /* just a dummy */
}
And yes: With plain C you can assign function pointers to each object. But that's not the same as virtual functions in C++.
Virtual table is per class. Virtual pointer is per object. See here http://www.go4expert.com/articles/virtual-table-vptr-t16544/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With