Here is my cpp code.
#include <iostream>
using namespace std;
class A {
public:
int val;
char a;
};
class B: public A {
public:
char b;
};
class C: public B {
public:
char c;
};
int main()
{
cout << sizeof(A) << endl;
cout << sizeof(B) << endl;
cout << sizeof(C) << endl;
return 0;
}
The output of the program (in gcc) is:
8
12
12
This output confuses me a lot.
I know that the alignment may be the reason why sizeof(A) equals to 8. (sizeof(int) + sizeof(char) + 3 bytes padding
)
And I also guess that the expansion of sizeof(B) (sizeof(B) == sizeof(A) + sizeof(char) + 3 bytes padding
) is to avoid overlap when copy occurs. (is that right?)
But what I really don't know why sizeof(B) is equal to sizeof(C).
Thanks a lot.
cout << "Offset of 'val': " << (int)(&((C*)0)->val) << " bytes.\n";
etc. – Lelia