#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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With