sizeof(object) in C++

Hi,

I have defined the class and call the sizeof(object to class) to get the size.

# include <iostream>
# include <iomanip>

using namespace std;
class sample
{
	private:
		int i;
		float j;
		char k;

	public:
		sample()
		{
		}
		
		sample(int a, float b, char c)
		{
			i=a;
			j=b;
			k=c;
		}

		void showdata()
		{
			cout<<"sizeof i="<<sizeof(i)<<endl;
			cout<<"sizeof j="<<sizeof(j)<<endl;
			cout<<"sizeof k="<<sizeof(k)<<endl;
			cout<<"i,j,k= "<<i<<"\t"<<j<<"\t"<<k<<endl;
		}
};

int main()
{
	sample q(3,4.5f,'Q'), w(3,5.67f,'W');
	q.showdata();
	cout<<"sizeof q is "<<sizeof(q)<<endl;
	cout<<"sizeof w is "<<sizeof(w)<<endl;
	return 0;
}

I expect the output of size of q and size of w to be "9" - since it is int+float+char(4+4+1)
However it returns 12. Can anybody explain why is it so??

Output as follows:

ganesh@ubuntu:~/my_programs/cpp/letuscpp$ g++ p22.cpp
ganesh@ubuntu:~/my_programs/cpp/letuscpp$ ./a.out
sizeof i=4
sizeof j=4
sizeof k=1
i,j,k= 3	4.5	Q
sizeof q is 12
sizeof w is 12

Thanks,
Ramkrix

Data structures in both C and C++ often will have packing/padding to make the elements in the structure aligned to word boundaries.

Data structure alignment - Wikipedia, the free encyclopedia

1 Like

Hi Citaylor,

Thank you very much for the link. Now I am clear with it. Thanks once again!!