Derived classes in C - What is your favorite method?

后端 未结 9 1254
既然无缘
既然无缘 2020-12-17 04:10

In my experience in object oriented C programming I have seen two ways to implement derived classes.


First Method, have a definition of the pa

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 04:25

    I prefer the first method because you can cast the derived class pointer to the parent class without any worries.

    It's the other way round.

    The C standard guarantees that the address of a struct is the address of the first member, so in the second case it is safe to cast a pointer to derived to parent, as the first member of derived is the parent struct, and a the struct as a member as the same layout as the same struct when not a member, so casting a pointer to a derived to parent will always work.

    The same is not true for the second case. Two structs with some members defined as the same type may have different padding between those members.

    It would be reasonable for a 64 bit bigendian compiler to compile

    struct A { a uint64_t; b uint32_t; };
    

    such that sizeof(A) is a whole multiple of 8 and b is 64 bit aligned, but compile

    struct B { a uint64_t; b uint32_t; c uint32_t; };
    

    so that sizeof(B) is a whole multiple of 8, but b is only 32 bit aligned so that it doesn't waste space.

提交回复
热议问题