C++ Programming - Empty Base Class Optimization

It is know that a class without any non-static data members will be having a size of 1 byte.

class A {
static int i;
}; // sizeof(A) will be 1


Now suppose that we inherited this to create another empty (no non-static member) class B, as follow


class B: public A {

}; // Still sizeof(B) will be 1 instead of 2 bytes


Now lets take the case in which the inherited class has a non-static data member.

class C: public C {
int element;
}; // This time sizeof(C) will be 4

This time instead of 4 + 1 = 5 bytes it gave 4 bytes, this was because of the base class optimization.

Note: I will be refering sizeof(int) as 4bytes

Labels: ,


About this entry