This is the output of the given program:
sizeof(Empty) 1
sizeof(Derived1) 1
sizeof(Derived2) 4
sizeof(Derived3) 1
sizeof(Derived4) 8
sizeof(Dummy) 1
This is the program:
#include <iostream>
using namespace std;
class Empty
{};
class Derived1 : public Empty
{};
class Derived2 : virtual public Empty
{};
class Derived3 : public Empty
{
char c;
};
class Derived4 : virtual public Empty
{
char c;
};
class Dummy
{
char c;
};
int main()
{
cout << "sizeof(Empty) " << sizeof(Empty) << endl;
cout << "sizeof(Derived1) " << sizeof(Derived1) << endl;
cout << "sizeof(Derived2) " << sizeof(Derived2) << endl;
cout << "sizeof(Derived3) " << sizeof(Derived3) << endl;
cout << "sizeof(Derived4) " << sizeof(Derived4) << endl;
cout << "sizeof(Dummy) " << sizeof(Dummy) << endl;
return 0;
}
Size of Derived3 is 1 byte. Then why the size of Derived 4 is 8 bytes?? If alignment is the answer then why there is no alignment in case of derived3?
It depends on alignments of data members within a class. It seems that if a class has a virtual base class then its realization contains a reference to this virtual base class that in your case is equal to 4 bytes. When you add data member of type char then it is padded with three bytes that to provide the alignment for the reference to the base virtual class.