简体   繁体   中英

C struct Inheritance vs C++ POD struct Inheritance

Suppose I use the fairly common idiom to define struct inheritance in my_header.h :

struct A { int a_field; ... };
struct B { struct A _as_A; int b_field; ... };

Now in my C code I can do binstance._as_A.a_field , or I can cast a pointer to B to a pointer to A, and so forth.

My question is this. Suppose that I now define a new C++ header my_header.hpp :

struct A { int a_field; ... }
struct B : A { int b_field; ... }

Suppose I do this taking care to make sure B is a POD type .

Am I guaranteed that the memory layout of a B instance is the same in C and C++?

Suppose I do this taking care to make sure B is a POD type.

As pointed out in the comments, B will never be a POD type, because it will never be a standard-layout class.

7 A standard-layout class is a class that:

[...]

(7.5) -- either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and

[...]

10 A POD struct 110 is a non-union class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). Similarly, a POD union is a union that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). A POD class is a class that is either a POD struct or a POD union.

Because of that, the literal question you asked turns out irrelevant: even if the layout order were guaranteed, you still wouldn't be allowed to do what you're trying to do. This matters because concrete implementations do typically define the layout order the way you're hoping, as part of the ABI, but that's not enough for what you're after.

No. The C++ standard draft N4296 states:

10 Derived classes
5 The order in which the base class subobjects are allocated in the most derived object (1.8) is unspecified. [...]
8 [ Note: A base class subobject might have a layout (3.7) different from the layout of a most derived object of the same type. [...] ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM