The size of a struct should usually be the sum of the sizes of the data members, but this is not the case. For example,
#include <iostream>
#include <iomanip>
struct SomeStruct
{
short a{};
int b{};
};
int main(int argc, char const *argv[])
{
std::cout << std::left;
std::cout << std::setw(16) << "short:" << sizeof(short) << " bytes\n";
std::cout << std::setw(16) << "int:" << sizeof(int) << " bytes\n";
std::cout << std::setw(16) << "SomeStruct:" << sizeof(SomeStruct) << " bytes\n";
return 0;
}It should print the sizes as follows,
short: 2 bytes
int: 4 bytes
SomeStruct: 8 bytes
SomeStruct size is 2 bytes larger. This happens because compiler add some gaps in the structures which are called padding, for performance reasons.
Tip
We can reduce the padding size by defining data members in decreasing size order.