This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: sizeof with virtual inheritance


Eljay Love-Jensen writes:
> The structure has extra bookkeeping information to keep track.
> 
> For example, if you have multiple inheritance of:
> foo : bar
> baz : bar
> quux : foo, baz
> 
> The memory layout of quux is going to be:
> [...]

Hi, sorry for the late reply

Your comments apply generally to multiple inheritance, you didn't say anything
about virtual inheritance. Besides, for non-virtual multiple inheritance, there
seems to be no extra data in the objects.
Here is a program that shows what I'm talking about:

//--------8<---------
#include <iostream>

using namespace std;

class c1{char x;};
class c2:public c1{};
class c3:public c1{};
class c4:virtual public c1{};
class c5:virtual public c1{};
class c6:public c2, public c3{};
class c7:public c4, public c5{};

#define S(x) cout<<"c"#x<<": "<<sizeof(c##x)<<endl;

int main()
{
	S(1)S(2)S(4)S(6)S(7)
	cin.get();
}
//------->8---------

I compiled it with mingw - gcc 3.2 (in Windows) and here are the results:

c1: 1
c2: 1
c4: 8
c6: 2
c7: 12

I had the same results on a linux system too.

As you can see, the only difference between c2 and c4 is the virtual
inheritance, yet the size difference is 7 bytes (it probably has an extra 4-byte
pointer aligned at a 4-byte offset).
Classes c6 and c7 have multiple inheritance (basically they both inherit c1
twice, indirectly), and again the difference is virtual inheritance.
c6 really gets 2 copies of c1, so the size is 2.
But c7 should only get 1 copy of c1 because of the virtual inheritance; yet its
size is 12, which suggests it has 2 extra pointers or something.

I'd like to know what's that extra data used for and why it is necessary. I'd
also like to know when and where it is added, because I haven't managed to find
an algorithm to calculate the size based on the inheritance graph.

Thanks
Adrian


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]