Virtual Methods or Function Pointers

后端 未结 8 1446
春和景丽
春和景丽 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).

    0 讨论(0)
  • 2020-12-07 12:34

    Function pointers are more C-style I would say. Mainly because in order to use them you usually must define a flat function with the same exact signature as your pointer definition.

    When I write C++ the only flat function I write is int main(). Everything else is a class object. Out of the two choices I would choose to define an class and override your virtual, but if all you want is to notify some code that some action happened in your class, neither of these choices would be the best solution.

    I am unaware of your exact situation but you might want to peruse design patterns

    I would suggest the observer pattern. It is what I use when I need to monitor a class or wait for some sort of notification.

    0 讨论(0)
提交回复
热议问题