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

后端 未结 6 437
清歌不尽
清歌不尽 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条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 17:45

    Its heavily implementation dependent, but generally you'll get one vtable object per class that has any virtual functions (classes with no virtual functions or bases don't need them), and one vptr per object of a class with a vtable (pointing at the class's vtable).

    Things get more complex if you have multiple inheritance and virtual base classes -- which can be implemented many ways. Some implementations use an addition vtable per additional base class (so you end up with a vtable per base class per class), while others use a single vtable with extra info in it. This may result in needing multiple vptrs per object.

    The virtual keyword in B is irrelevant -- if the function is virtual in the base class, it will be virtual in the derived classes regardless.

提交回复
热议问题