Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   Question regarding the size of the class (http://www.velocityreviews.com/forums/t962270-question-regarding-the-size-of-the-class.html)

 somenath 06-29-2013 06:29 AM

Question regarding the size of the class

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