Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is virtual table per object or per class? [duplicate]

Tags:

c++

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?

like image 775
kadina Avatar asked Jul 08 '15 18:07

kadina


3 Answers

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 :)

like image 63
Gerald Avatar answered Sep 26 '22 03:09

Gerald


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++.

like image 25
ikrabbe Avatar answered Sep 22 '22 03:09

ikrabbe


Virtual table is per class. Virtual pointer is per object. See here http://www.go4expert.com/articles/virtual-table-vptr-t16544/

like image 30
Ashot Avatar answered Sep 25 '22 03:09

Ashot