I want to understand the layout of an object. So I executed with different orders of member variables. Everything came as expected, expect for following sequence.
#include <iostream>
using namespace std;
class Test1
{
public:
int m_a;
char m_b;
};
class Test
{
public:
int m_b;
Test1 m_t;
char m_g;
char m_c;
char m_d;
int m_e;
};
int main()
{
Test t;
cout<<(int*)(&t.m_b)<<endl;
cout<<(int*)(&t.m_t.m_a)<<endl;
cout<<(int*)(&t.m_t.m_b)<<endl;
cout<<(int*)(&t.m_c)<<endl;
cout<<(int*)(&t.m_d)<<endl;
cout<<(int*)(&t.m_e)<<endl;
cout<<sizeof(t)<<endl;
}
Output:
0xbfebbd6c
0xbfebbd70
0xbfebbd74
0xbfebbd79
0xbfebbd7a
0xbfebbd7c
20
Where as I expected 16.
But If i remove m_a from Test1, it is giving expected input(12).
#include <iostream>
using namespace std;
class Test1
{
public:
char m_b;
};
class Test
{
public:
int m_b;
Test1 m_t;
char m_g;
char m_c;
char m_d;
int m_e;
};
int main()
{
Test t;
cout<<(int*)(&t.m_b)<<endl;
cout<<(int*)(&t.m_t.m_b)<<endl;
cout<<(int*)(&t.m_c)<<endl;
cout<<(int*)(&t.m_d)<<endl;
cout<<(int*)(&t.m_e)<<endl;
cout<<sizeof(t)<<endl;
}
Output:
0xbf82e674
0xbf82e678
0xbf82e67a
0xbf82e67b
0xbf82e67c
12
Why there is the difference of 8 bytes if i remove integer which is exactly aligned to 4 bit boundary?
PS: I know this is implementation specific. I want to know how that implementation was done :). This was come into picture since i want to access private members, so trying to understand object layout !!!
With integer m_a
sizeof(Test1)
is 8 to align m_a
to 4byte boundary. Without the int, it is only the size of th char
.
class Test
{
public:
int m_b; // 4
Test1 m_t; // 12
char m_g; // 13
char m_c; // 14
char m_d; // 15
int m_e; // 20
};