Class sizes with virtual inheritance in C++

前端 未结 5 1881
[愿得一人]
[愿得一人] 2021-01-02 20:48
#include

using namespace std;

class abc
{
    int a;
};
class xyz : public virtual abc
{
    int b;
};

int main()
{
    abc obj;
    xyz obj1;
            


        
5条回答
  •  攒了一身酷
    2021-01-02 21:28

    A good article on virtual and multiple inheritance in GCC is this one (Internet Archive Permalink):

    http://phpcompiler.org/articles/virtualinheritance.html

    Yet it doesn't quite answer your question, as you are getting an output of 20 bytes out of whatever (unspecified) compiler and build settings you are using.

    If you were using GCC (under the default settings IDEone uses, at least), then you would be getting 12 bytes. Which is the same thing as what it would give had you written:

    class abc
    {
        int a;
        virtual void foo() {}
    };
    class xyz : public abc
    {
        int b;
    };
    

    Were you to virtually inherit from abc when it contains virtual methods:

    class abc
    {
        int a;
        virtual void foo() {}
    };
    class xyz : virtual public abc
    {
        int b;
    };
    

    ...then you would get 16 bytes out of GCC.

    Why is the extra space being taken up exactly? I suspect it is for the vptr table or something of that sorts but don't know for certain.

    If I had to make a wild guess about your 16 byte variance: I might look into if your compiler's implementation of virtual inheritance treats all virtual base classes as if they had virtual methods, even if they didn't?

    But I pretty much made that up. You'll have to look further under the hood if you want to test the theory; it's implementation-dependent.

提交回复
热议问题