# Thread: Help with virtual function and virtual inheritance

1. ## Help with virtual function and virtual inheritance

hi, anyone can help me. i have below codes
Code:
```class A
{
char k;
public:
virtual void aa() {}
};
class B : public virtual A
{
char j;
public:
virtual void bb() {}
};

class C : public virtual B
{
char i;
public:
virtual void cc() {}
};

class D : public B, public C
{
char l;
virtual void dd() {}
};
int main (int argc, char *argv[]) {
cout << "A: " << sizeof(A) << endl
<< "B: " << sizeof(B) << endl
<< "C: " << sizeof(C) << endl
<< "D: " << sizeof(D) << endl;
return 0;
}```
the output is
A: 8
B: 16
C: 24
D: 36

I don't why , especially the last one.
I know The A is 8, because there is a pointer point to the virtual function table as well.
In B and C, if there are no virtual, the output would be B: 12, C: 16 and D would be 28.
so can anybody explain to me why this happens, what's the principle. 2. I had to draw a picture to help myself:

Attachment 9975

Let's consider the culmination of the hierarchy, D. When you make a D you have two ways to make an A: through C's initialization or B's initialization. The use of the virtual keyword makes sure that, whatever actually happens, there is only one A in the class. Which A you get depends on the order of construction of the B and C sub-objects.

Perhaps the size makes more sense when you consider those facts. Suppose a C is constructed (but before that, A and B are constructed in turn) and then D is constructed. This means that the parts unique to D are 12 bytes long. Four are probably used to contain your array (with one byte for padding). The other 8 are probably the v-table(s). That's my best guess at any rate.

Maybe if you understand the structure A->B->C->D better, then you should use it? 3. Originally Posted by shaxquan hi, anyone can help me. i have below codes
Code:
```class A
{
char k;
public:
virtual void aa() {}
};
class B : public virtual A
{
char j;
public:
virtual void bb() {}
};

class C : public virtual B
{
char i;
public:
virtual void cc() {}
};

class D : public B, public C
{
char l;
virtual void dd() {}
};
int main (int argc, char *argv[]) {
cout << "A: " << sizeof(A) << endl
<< "B: " << sizeof(B) << endl
<< "C: " << sizeof(C) << endl
<< "D: " << sizeof(D) << endl;
return 0;
}```
the output is
A: 8
B: 16
C: 24
D: 36

I don't why , especially the last one.
I know The A is 8, because there is a pointer point to the virtual function table as well.
In B and C, if there are no virtual, the output would be B: 12, C: 16 and D would be 28.
so can anybody explain to me why this happens, what's the principle. Popular pages Recent additions 