C++ object size with virtual methods

前端 未结 6 544
北荒
北荒 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:11

    This obviously depends on the compiler implementation. Anyway I think that I can sum up the following rules from the implementation given by a classic paper linked below and which gives the number of bytes you get in your examples (except for class D which would be 36 bytes and not 32!!!):

    The size of an object of class T is:

    • The size of its fields PLUS the sum of the size of every object from which T inherits PLUS 4 bytes for every object from which T virtually inherits PLUS 4 bytes ONLY IF T needs ANOTHER v-table
    • Pay attention: if a class K is virtually inherited multiple times (at any level) you have to add the size of K only once

    So we have to answer another question: When does a class need ANOTHER v-table?

    • A class that does not inherit from other classes needs a v-table only if it has one or more virtual methods
    • OTHERWISE, a class needs another v-table ONLY IF NONE of the classes from which it non virtually inherits does have a v-table

    The End of the rules (which I think can be applied to match what Terry Mahaffey has explained in his answer) :)

    Anyway my suggestion is to read the following paper by Bjarne Stroustrup (the creator of C++) which explains exactly these things: how many virtual tables are needed with virtual or non virtual inheritance... and why!

    It's really a good reading: http://www.hpc.unimelb.edu.au/nec/g1af05e/chap5.html

提交回复
热议问题