C++ object size with virtual methods

前端 未结 6 543
北荒
北荒 2020-11-27 04:47

I have some questions about the object size with virtual.

1) virtual function

class A {
    public:
       int a;
       virtual voi         


        
6条回答
  •  独厮守ぢ
    2020-11-27 05:32

    All of this is completely implementation defined you realize. You can't count on any of it. There is no 'rule'.

    In the inheritance example, here is how the virtual table for classes A and B might look:

          class A
    +-----------------+
    | pointer to A::v |
    +-----------------+
    
          class B
    +-----------------+
    | pointer to A::v |
    +-----------------+
    | pointer to B::w |
    +-----------------+
    

    As you can see, if you have a pointer to class B's virtual table, it is also perfectly valid as class A's virtual table.

    In your class C example, if you think about it, there is no way to make a virtual table that is both valid as a table for class C, class A, and class B. So the compiler makes two. One virtual table is valid for class A and C (mostly likely) and the other is valid for class A and B.

提交回复
热议问题