Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct attribute inheritance in c++

Tags:

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.

like image 879
squater Avatar asked Sep 21 '12 12:09

squater


1 Answers

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.
like image 125
tenfour Avatar answered Oct 04 '22 21:10

tenfour