Size of Class/Object

Two queries:
1. why size of Base class object is getting 8 bytes instead of 5 bytes(1 for char + 4 for int)?
2. And size of class is equals to size of object is same?
Note: OS - 64-bit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

class Base
{
 int i;
 char c;
};

int main()
{
 Base obj;
 cout<<"size of Base class "<<sizeof(Base)<<endl;
 cout<<"size of Base obj "<<sizeof(obj)<<endl;
 return 0;
}

Output
size of Base class 8
size of Base obj 8
1. why size of Base class object is getting 8 bytes instead of 5 bytes(1 for char + 4 for int)?
It's to preserve alignment of members in memory.
If you had Base twothings[2];, then twothings[1].i would be at an odd address, and would be very bad news.

2. And size of class is equals to size of object is same?
Would you expect something different if you had done this?
1
2
3
int foo;
 cout<<"size of type "<<sizeof(int)<<endl;
 cout<<"size of obj "<<sizeof(foo)<<endl;

The size of a type, and the size of an object of that type are always the same thing.
> then twothings[1].i would be at an odd address, and would be very bad news.
¿care to expand that part?
Topic archived. No new replies allowed.