Search code examples
c++inheritanceg++bit-fieldspacked

Packing bitfields even more tightly


I have a problem with bitfields in derived classes.

With the g++ compiler, you can assign __attribute__((packed)) to a class and it will pack bitfields. So

class A
{
  public:
    int one:10;
    int two:10;
    int three:10;
} __attribute__ ((__packed__));

takes up only 4 bytes. So far, so good.
However, if you inherit a class, like this

class B
{
  public:
    int one:10;
    int two:10;
} __attribute__ ((__packed__));

class C : public B
{
  public:
    int three:10;
} __attribute__ ((__packed__));

I would expect class C, which has the same content as class A above, to have the same layout as well, i.e. take up 4 bytes. However, C turns out to occupy 5 bytes.

So my question is, am I doing something wrong, and if so, what? Or is this a problem with the compiler? An oversight, a real bug?

I tried googling, but haven't really come up with anything, apart from a difference between Linux and Windows (where the compiler tries to emulate MSVC), which I'm not interested in. This is just on Linux.


Solution

  • I believe the problem is with B, which cannot easily be 2.5 bytes. It has to be at least 3 bytes.

    Theoretically, the derived class might be allowed to reuse padding from the base class, but I have never seen that happen.