Question regarding the size of the class

S

somenath

I am not able to understand why the sizeof the class B is 8
I have the following program.
#include<iostream>
using namespace std;

class X {
};
class Y : public virtual X {};
class Z : public virtual X {};
class A : public Y, public Z {};
int main (void)
{
cout<<"Sizeof int = "<<sizeof(int)<<endl;
cout<<"Sizeof void* = "<<sizeof(void*)<<endl;
cout<<"Sizeof int* = "<<sizeof(int*)<<endl;
cout<<"Size of X = "<<sizeof (X)<<endl;
cout<<"Size of Y = "<<sizeof (Y)<<endl;
cout<<"Size of Z = "<<sizeof (Z)<<endl;
cout<<"Size of A = "<<sizeof (A)<<endl;
return 0;
}
Output
Sizeof int = 4
Sizeof void* = 8
Sizeof int* = 8
Size of X = 1
Size of Y = 8
Size of Z = 8
Size of A = 16

According to my understanding the sizeof class Y would be sum of sizeof(class X) + sizof(virtual_table_pointer) + sizeof padding for alignment required.

So in this case sizeof(class X) = 1 + sizeof(virtual_table_pointer) = 8 (not sure about this ) + size of padding for alignment requirement ( 3) = 12

So I am not able to understand why the sizeof y is printed as 8?

Now when I change the program as the following way (introduce one public variable in class X)
#include<iostream>
using namespace std;

class X {
public:
int x;

};
class Y : public virtual X {};
class Z : public virtual X {};
class A : public Y, public Z {};

int main (void)
{
cout<<"Sizeof int = "<<sizeof(int)<<endl;
cout<<"Sizeof void* = "<<sizeof(void*)<<endl;
cout<<"Sizeof int* = "<<sizeof(int*)<<endl;
cout<<"Size of X = "<<sizeof (X)<<endl;
cout<<"Size of Y = "<<sizeof (Y)<<endl;
cout<<"Size of Z = "<<sizeof (Z)<<endl;
cout<<"Size of A = "<<sizeof (A)<<endl;
return 0;

}

I get the following output

Sizeof int = 4
Sizeof void* = 8
Sizeof int* = 8
Size of X = 4
Size of Y = 16
Size of Z = 16
Size of A = 24

Once again I am not able to understand why the sizeof Y is 16?


According to my understanding the sizeof Y would be sizeof X (4) + sizeof (virtual_table_pointer) 8 + padding required for alignment ( 0 ) = 12
But why it is 16 ? Please help me to understand this concept.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,150
Members
46,697
Latest member
AugustNabo

Latest Threads

Top