Inheriting the Struct attribute in C ++

Are attributes of a structure inherited in C ++

eg:

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

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

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

I can not add attribute (( packed )) into structure B without warning the compiler:

ignoring packed attribute because of unpacked non-POD field

So, I know that the whole structure of B will not be packed, which is good in my use case, but I need the fields of struct A to be packed in struct B.

+5
source share
2 answers

Yes, members Awill be packaged in struct B. It must be so, otherwise it will break the whole purpose of inheritance. For instance:

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.
+4
source

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

. - . :

#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;
}

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

, < > member, -POD- . . POD ++?

+4

All Articles