Virtual Methods or Function Pointers

后端 未结 8 1470
春和景丽
春和景丽 2020-12-07 11:31

When implementing polymorphic behavior in C++ one can either use a pure virtual method or one can use function pointers (or functors). For example an asynchronous callback c

8条回答
  •  误落风尘
    2020-12-07 12:27

    Approach 1

    • Easier to read and understand
    • Less possibility of errors (iFunc cannot be NULL, you're not using a void *iParam, etc
    • C++ programmers will tell you that this is the "right" way to do it in C++

    Approach 2

    • Slightly less typing to do
    • VERY slightly faster (calling a virtual method has some overhead, usually the same of two simple arithmetic operations.. So it most likely won't matter)
    • That's how you would do it in C

    Approach 3

    Probably the best way to do it when possible. It will have the best performance, it will be type safe, and it's easy to understand (it's the method used by the STL).

提交回复
热议问题