squater
squater

Reputation: 189

Struct attribute inheritance in c++

Are the attributes of a struct inherited in C++

eg:

struct A {
    int a;
    int b;
}__attribute__((__packed__));

struct B : A {
    list<int> l;
};

will the inherited part of struct B (struct A) inherit the packed attribute?

I cannot add an a attribute((packed)) to struct B without getting a compiler warning:

ignoring packed attribute because of unpacked non-POD field

So I know that the entire struct B will not be packed, which is fine in my use case, but I require the fields of struct A to be packed in struct B.

Upvotes: 5

Views: 3186

Answers (2)

Andreas Fester
Andreas Fester

Reputation: 36630

Will the inherited part of struct B (struct A) inherit the packed attribute?

Yes. The inherited part will still be packed. But the pack attribute itself is not inherited:

#include <stdio.h>

#include <list>
using std::list;

struct A {
    char a;
    unsigned short b;
}__attribute__((__packed__));

struct B : A {
    unsigned short d;
};

struct C : A {
    unsigned short d;
}__attribute__((__packed__));

int main() {
   printf("sizeof(B): %lu\n", sizeof(B));
   printf("sizeof(C): %lu\n", sizeof(C));

   return 0;
}

When called, I get

sizeof(B): 6
sizeof(C): 5

I think your warning comes from the list<> member which is a non-POD type and itself not packed. See also What are POD types in C++?

Upvotes: 5

tenfour
tenfour

Reputation: 36896

Yes, the members of A will be packed in struct B. It must be this way, otherwise it would break the whole point of inheritance. For example:

std::vector<A*> va;
A a;
B b;
va.push_back(&a);
vb.push_back(&b);

// loop through va and operate on the elements. All elements must have the same type and behave like pointers to A.

Upvotes: 4

Related Questions