Home > Enterprise >  Why is my class size appending an extra byte?
Why is my class size appending an extra byte?

Time:11-16

I have the following class structure:

#pragma pack(push, 1)
class Base{ 
   Base(){}
    ~Base{}
    void accept();
};

class A : Base{
    int m1;
    int m2;
    int m3;
};

class B : Base{
    A a;
    int m1;
    int m2;
    int m3;
    int m4;
};
#pragma pack(pop)

Size of B in this case is 29 bytes.

However, when I make class A not inherit from Base, but B still inherits from Base, Class B becomes 28 bytes.

Then if I make class A inherit from Base but B not inherit from base Class B also becomes 28 bytes.

So only when both A and B inherit from Base does my class B's size go from 28 -> 29 bytes.

What is happening that would cause this behavior?

CodePudding user response:

The C object model doesn't allow two distinct subobjects of the same type to exist at the same address.

https://eel.is/c draft/intro.object#9

Two objects with overlapping lifetimes that are not bit-fields may have the same address if one is nested within the other, or if at least one is a subobject of zero size and they are of different types; otherwise, they have distinct addresses and occupy disjoint bytes of storage.

Here your two subobjects (B::Base)b and (A::Base)(b.a) both have zero size, but they are not of different types, therefore they require distinct addresses.

  •  Tags:  
  • c
  • Related