Why derived class does not have the vtable pointer and used instead vtable of the base class?

StackOverflow https://stackoverflow.com/questions/19588993

Pergunta

I am interested in the implementation of a virtual function in pure C. Here an example of the implementation. Then the implementation of the derived class through a pointer to the virtual functions table of the base class. Why derived class does not have the vtable pointer and used instead vtable of the base class. Maybe because they are the same offset ?

void myClassDerived_ctor(struct myClassDerived *this)
{
    myClassBase_ctor(&this->base);
    this->base.vtable = (void*)&myClassDerived_vtable + sizeof(void*); // used vtable of the base class
}
Foi útil?

Solução

It has to use the base class's vtable. The whole point is it looks just like a base class, but has different entries in the vtable. Hence it's polymorphicly different behaviour.

Outras dicas

It does have its own vtable. It uses the base class's vtable pointer to point to it, so that code that knows only about the base class can correctly call virtual functions that are overridden in derived classes.

This is done to make polymorphism to work correctly. The same object can be pointed by either base class's pointer or derived class's pointer. If you call a virtual function, then in both cases it has to call the same function (the function of derived class). So the derived class makes the base class's vtable pointer to point it's own vtable so that in all cases, the object will use the correct vtable.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top