Hello,

Suppose I have two classes, MyClassX and MyClassY, each with two member variables, as defined below. I create an object instance of each class, and then create a pointer to each member variable for each object:

Code:
class MyClassX
{
public:

	int a;
	double b;

	MyClassX(int _a, double _b)
	{
		a = _a;
		b = _b;
	};
};


class MyClassY
{
public:

	int a;
	int b;

	MyClassY(int _a, int _b)
	{
		a = _a;
		b = _b;
	};
};


int main()
{
	MyClassX x(1, 2.0);
        void* pxa = &x.a;
	void* pxb = &x.b;
        int sx = sizeof(MyClassX);

	MyClassY y(1, 2);
        void* pya = &y.a;
	void* pyb = &y.b;
        int sy = sizeof(MyClassY);

        return 0;
}

The address I get are:

pxa = 20ef38
pxb = 20ef40

pya = 20ef78
pyb = 20ef7c

And the class sizes are:

sx = 16.
sy = 8.

After converting the hexadecimal to decimal, it appears that with MyClassX, pxb is 8 bytes from pxa, whereas for MyClassY, pya is only 4 bytes from pyb. This makes sense for MyClassY, because the first member variable to be stored is an int, and so will occupy 4 bytes. However, why should this be any different for MyClassX, which also has an int as the first member variable, so shouldn't this also occupy 4bytes?

The reason I have come across this problem is that I am looking into streaming objects to memory and then loading them again. (I know boost can do this, but I am trying it out myself from scratch.) Therefore, this is causing an issue, because I cannot just assume that the size of memory occupied by an object is just the sum of the sizes of its member variables. MyClassX is 8 bytes larger than MyClassY, even though the intuition is that it should only occupy 4 bytes more due to a double being replaced by an int.

Thanks for any help!