sizeof an object in visual c++

Hello,

I am experimenting with the results of sizeof on a WinXP machine Visual C++ 2008 express compiler. I have a class defined with a few members:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ifndef __TEST_H__
#define __TEST_H__

class Point {
private:

	int x;
	int y;
	char ch;
    
	Point();
	virtual int getValueX(void);
	int getValueY(void);
};
#endif 


and the .cpp caller like this:

1
2
3
4
5
6
7
8
9
10
#include "c:\Development\C++ Practice\practice\practice\test.h"
#include <stdio.h>

int s;
int main()
{
	Point p();
	s = sizeof(Point);
	printf("%d\n", s);
}


When the char member is uncommented, and the rest are commented out, such as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ifndef __TEST_H__
#define __TEST_H__

class Point {
private:

	// int x;
	// int y;
	char ch;
    
	// Point();
	// virtual int getValueX(void);
	// int getValueY(void);
};
#endif 


my output is '1'

However, when I uncomment the int's, such as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ifndef __TEST_H__
#define __TEST_H__

class Point {
private:

	int x;
	int y;
	char ch;
    
	// Point();
	// virtual int getValueX(void);
	// int getValueY(void);
};
#endif 


The two ints are 4 bytes each (32-bit system), and the char should be 1 byte, so I am expecting the output to be '9', but my actual output is '12' ???

What causes the char to jump from 1 byte to 4 bytes in size when the ints are uncommented?
just realized that the compiler aligns on 4-byte boundaries. I guess when there is more than one member, it aligns. Is there a way to prevent this from happening?
Last edited on
I doubt there's a standard way to do it, but you can take a look at this: http://msdn.microsoft.com/en-us/library/83ythb65.aspx
Topic archived. No new replies allowed.