Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class sizes with virtual inheritance in C++

#include<iostream>

using namespace std;

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

int main()
{
    abc obj;
    xyz obj1;
    cout<<endl<<sizeof(obj);
    cout<<endl<<sizeof(obj1);
    return 0;
}

The answers would be compiler dependent but I'm surprized when I saw this as the result

~/Documents/workspace/tmp ‹.rvm-›  $ ./class_sizes   

4
16

If I remove the virtual keyword then the size allocated is 4 and 8 respectively which is what I expected.

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.

like image 473
nikhil Avatar asked Nov 12 '11 16:11

nikhil


1 Answers

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.

like image 191
HostileFork says dont trust SE Avatar answered Oct 02 '22 02:10

HostileFork says dont trust SE