Why should virtual functions not be used excessively?

前端 未结 10 2108
再見小時候
再見小時候 2021-02-19 13:16

I just read that we should not use virtual function excessively. People felt that less virtual functions tends to have fewer bugs and reduces maintenance.

What kind of b

10条回答
  •  逝去的感伤
    2021-02-19 13:20

    We recently had a perfect example of how misuse of virtual functions introduces bugs.

    There is a shared library that features a message handler:

    class CMessageHandler {
    public:
       virtual void OnException( std::exception& e );
       ///other irrelevant stuff
    };
    

    the intent is that you can inherit from that class and use it for custom error handling:

    class YourMessageHandler : public CMessageHandler {
    public:
       virtual void OnException( std::exception& e ) { //custom reaction here }
    };
    

    The error handling mechanism uses a CMessageHandler* pointer, so it doesn't care of the actual type of the object. The function is virtual, so whenever an overloaded version exists the latter is called.

    Cool, right? Yes, it was until the developers of the shared library changed the base class:

    class CMessageHandler {
    public:
       virtual void OnException( const std::exception& e ); //<-- notice const here
       ///other irrelevant stuff
    };
    

    ... and the overloads just stopped working.

    You see what happened? After the base class was changed the overloads stopped to be the overloads from C++ point of view - they became new, other, unrelated functions.

    The base class had the default implementation not marked as pure virtual, so the derived classes were not forced to overload the default implementation. And finally the functon was only called in case of error handling which isn't used every here and there. So the bug was silently introduced and lived unnoticed for a quite long period.

    The only way to eliminate it once and for all was to do a search on all the codebase and edit all the relevant pieces of code.

提交回复
热议问题