Derived classes in C - What is your favorite method?

后端 未结 9 1256
既然无缘
既然无缘 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条回答
  •  情书的邮戳
    2020-12-17 04:38

    I have used method #2 before and found it works quite ok:

    • you can upcast to the base type anytime if it is the first member in derived type
    • instead of dereferencing all the time to get at base members, just keep two pointers: one for the base interface, one for the derived interface

    free() on the pointer to the base structure will of course also free up the derived fields, so that isn't an issue...

    Also, I find accessing base fields something I tend to do in a polymorphic situation: I only care about those fields in methods that care about the base type. Fields in the derived type are used in methods only interested in the derived type.

提交回复
热议问题