sizeof operator doesn't work properly in call with static data members

B

balasubramaniam

I comile the code in unix where sizof(int)=4
#include<iostream>
using namespace std;

class A
{
int i;
static int j;
};
int A::j = 10;
int main()
{
cout<<sizeof(A)<<endl;

}
both i,j are members of class A.so sizeof(A) should be printed as 8.
But i get 4.
could anyone explain this behavior.
 
T

Thore Karlsen

I comile the code in unix where sizof(int)=4
#include<iostream>
using namespace std;

class A
{
int i;
static int j;
};
int A::j = 10;
int main()
{
cout<<sizeof(A)<<endl;

}
both i,j are members of class A.so sizeof(A) should be printed as 8.
But i get 4.
could anyone explain this behavior.

sizeof(A) give you the size of an instance of class A. j is not stored
in any instance of A, it is stored separately and shared by every
instance.
 
A

Andrey Tarasevich

balasubramaniam said:
I comile the code in unix where sizof(int)=4
#include<iostream>
using namespace std;

class A
{
int i;
static int j;
};
int A::j = 10;
int main()
{
cout<<sizeof(A)<<endl;

}
both i,j are members of class A.so sizeof(A) should be printed as 8.

No.

Firstly, in general case size of class type cannot be calculated as
total size of its data members.

Secondly, static data members do not contrubute to size of class type.
 

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
474,436
Messages
2,571,696
Members
48,796
Latest member
Greg L.
Top