Sizeof a class with different data types

I comment result of each class in main.
but in my calculation it should be like those comment in front of each class name in class definition.
Why results are different with my calculation?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
  #include <iostream>
using namespace std;
class A {};

class B {//8
private:
  int num, den;//4 4
};

class C {//5
private:
  char a;
  int num;
};

class D {//12
private:
  char a;    //1
  int num;   //4
  short int x; //2
  int y;     //4
  char z;    //1
};

class E {//12
private:
  char a;    //1
  char z;    //1
  short int x; //2
  int num;   //4
  int y;     //4
};

class F {//10
private:
  char c;//1
  double x;//8
  char d;//1
};

int main() {
  cout << "sizeof(A)= " << sizeof(A) << '\n';//1
  cout << "sizeof(B)= " << sizeof(B) << '\n';//8
  cout << "sizeof(C)= " << sizeof(C) << '\n';//8
  cout << "sizeof(D)= " << sizeof(D) << '\n';//20
  cout << "sizeof(E)= " << sizeof(E) << '\n';//12
  cout << "sizeof(F)= " << sizeof(F) << '\n';//24
}
Last edited on
Because the compiler provides padding for optimal alignment of members.
Amount of padding depends on hardware architecture.

For example, at line 19, you're assuming an int begins on an odd byte boundary.
In most 32 bit implementations, ints begin on a 4 byte multiple.


Last edited on
Topic archived. No new replies allowed.