More specifically, a class, inheriting from an empty class, containing just a union whose members include an instance of the base data-less class, takes up more memory than just the union. Why does this happen and is there any way to avoid spending the extra memory?
The following code illustrates my question:
#include <iostream>
class empty_class { };
struct big : public empty_class
{
union
{
int data[3];
empty_class a;
};
};
struct small
{
union
{
int data[3];
empty_class a;
};
};
int main()
{
std::cout << sizeof(empty_class) << std::endl;
std::cout << sizeof(big) << std::endl;
std::cout << sizeof(small) << std::endl;
}
The output of this code, when compiled using gcc version 7.3.0 compiled with -std=c++17
(although, I get the same result using c++11 and c++14), is:
1
16
12
I would expect that the classes big and small should be of the same size; however strangely, big takes up more memory than small even though they both, seemingly, contain the same data.
Also even if the size of the array in the union is changed, the difference between the size of big and small is a constant 4 bytes.
-Edit:
It seems as though this behavior is not specific to classes with union data types. Similar behavior occurs in other similar situations where a derived class has a member with the base class type. Thanks to those who pointed this out.