Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ POD struct inheritance? Are there any guarantees about the memory layout of derived members

Let's say, I have a struct RGB and I want to create struct RGBA, which inherits RGB:

struct RGB {     unsigned char r;     unsigned char g;     unsigned char b; };  struct RGBA: RGB {     unsigned char a; }; 

Both will be used for reading uncompressed image data:

RGBA *pixel=static_cast<RGBA *>(image->uncompressed_data); 

Question: Is this safe, regarding the memory layout of struct RGBA? Does anyone guarantee, that:

  • unsigned char a comes after the RGB struct (not before)
  • There is no padding between struct RGB and the a parameter from struct RGBA?

will #pragma pack help here? It's all about memory layout during inheritance.

like image 353
Nuclear Avatar asked Mar 14 '14 12:03

Nuclear


People also ask

Do C structs support inheritance?

Yes. The inheritance is public by default.

Is struct inheritance public by default?

"a struct has public inheritance by default"

Can a struct inherit from a custom type?

Yes, struct can inherit from class in C++.


1 Answers

No, the layout is not guaranteed. The only guarantees are for standard-layout classes; and one of the conditions of such a class is that it

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

In other words, all data members must be in the same class, not in more than one.

like image 81
Mike Seymour Avatar answered Sep 23 '22 11:09

Mike Seymour