0

Possible Duplicate:
Why isn’t sizeof for a struct equal to the sum of sizeof of each member?
How is the size of a C++ class determined?

When I check the size of the class with single char variable, it's size is 1 Byte. But if we add an integer, suddenly it goes to 8. Can you please explain Why?

class Char
{
  char b;
};
class Int
{
  int a;
};
class A
{
  int a;
  char b;
};

int main()
{
  Char Cobj;
  cout<<"Char size: "<<sizeof(Cobj)<<endl;
  Int Iobj;
  cout<<"Int size: "<<sizeof(Iobj)<<endl;
  A aobj;
  cout<<"A size: "<<sizeof(aobj)<<endl;

  return 0;
}

The output is: Char size: 1 Int size: 4 A size: 8

Community
  • 1
  • 1
Naresh T
  • 309
  • 2
  • 14

1 Answers1

1

Because of padding - 3 dummy bytes will be added after A::b.

This is done to properly align A in, say, an array - the first member of A is an int, which has to have a specific alignment (4 or 8 bytes probably). So if you have

A arrayOfA[10];

the objects themselves have to be aligned to 4 or 8 bytes.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625