Saturday, June 29, 2013

Question regarding the size of the class

Newsgroup: comp.lang.c++

Subject: Question regarding the size of the class

From: somenath <somenathpal@...>

Date: Fri, 28 Jun 2013 23:29:56 -0700 (PDT)





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.











via Usenet Forums - Usenet Search,Free Usenet - comp.lang.c++ http://www.pocketbinaries.com/usenet-forums/showthread.php?31415-Question-regarding-the-size-of-the-class&goto=newpost

View all the progranning help forums at:

http://www.pocketbinaries.com/usenet-forums/forumdisplay.php?128-Coding-forums

No comments:

Post a Comment