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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top