Until you enter a virtual table (by adding a virtual method or destructor) into struct B and parent , the member of this structure is the first element, then it is safe to simply case B to A
Dropping A into B also safe, but only if the original pointer actually points to B , and not to something else, for example, only to structure A
If parent not the first member of struct B , you should use the container_of macro, for example, as shown in the Linux kernel. It works with member pointer offsets (i.e. you can find a good explanation here ).
In addition, by default, both structures will have the same alignment. I'm not sure how the compiler puts A in B if you configure one of the structure alignments. I think it depends on the compiler, but it is easy to understand.
If B has a virtual table, you must know the compiler internals in order to correctly convert pointers. For example, GCC on x86_64 adds 8 bytes of offset, so you must offset it manually when converting. But this will not work in the case of virtual inheritance (virtual base classes) to decide that you need to resort to using RTTI, etc. But this is beyond the scope of your question, and I would recommend that you do not go this way.
Hope this helps.
user405725
source share