From what i know, the size of a class in c++ depends on the below factors -
- Size of all non-static data members.
- Order of data members.
- If byte padding is enabled or not.
- Size of its immediate base class.
- The existence of virtual functions.
- Mode of inheritance (virtual inheritance).
Now I've created 2 classes as below -
class A{
int a;
short s;
int b;
char d;
};// kept a char at last on purpose to leave a "hole"
class B : public A{
char c;
};
now on checking the size of A and B I see
- size of A: 16
- size of B: 16
my assumption is the char c in class B is accommodated in "hole" left in class A.
But, whats confused me is the below scenario wherein I make the members public
class A{
public:
int a;
short d;
int b;
char s;
};
class B : public A{
public:
char c;
};
Now the size becomes
- size of A: 16
- size of B: 20
I cannot seem to understand the reason for this difference.