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

梦想的初衷 提交于 2019-12-08 07:39:00

问题


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
}

回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/19588993/why-derived-class-does-not-have-the-vtable-pointer-and-used-instead-vtable-of-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!