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)struct RGB
and the a parameter from struct RGBA
?will #pragma pack
help here? It's all about memory layout during inheritance.
Yes. The inheritance is public by default.
"a struct has public inheritance by default"
Yes, struct can inherit from class in C++.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With