Number of Virtual tables and Virtual Pointers in a C++ Program

后端 未结 6 427
清歌不尽
清歌不尽 2020-12-08 17:20

Let say we have below program:

class A
{     public:
      virtual fun(){};
};
class B:public A
{     public:
     virtual fun(){};
};
int main()
{
     A a1         


        
6条回答
  •  萌比男神i
    2020-12-08 17:48

    Virual table will be created only if atleast 1 virtual function is there in the Base class,which will be any way inherited to the derived classes.it doesnt matter even if you remove virtual keyword from derived class B because already u are having a virtual fun() in A. So the number of virtual tables will be 2(as its per class basis) and number of virtual ptrs will also be 2,as its per object basis. VTABLE for A---v_ptr* ,A::fun()

    & VTABLE for B--- V_ptr*(which was inherited from A),B::fun()/* B have access to both A::fun & B's fun(),but since we mentioned A::fun() as virtual B's virtual table is filled with the most derived version of the function,fun(),which is nothing but B::fun().Hope this clears ur doubt

提交回复
热议问题