Why should virtual functions not be used excessively?

前端 未结 10 1950
再見小時候
再見小時候 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:28

    In C++: --

    1. Virtual functions have a slight performance penalty. Normally it is too small to make any difference but in a tight loop it might be significant.

    2. A virtual function increases the size of each object by one pointer. Again this is typically insignificant, but if you create millions of small objects it could be a factor.

    3. Classes with virtual functions are generally meant to be inherited from. The derived classes may replace some, all or none of the virtual functions. This can create additional complexity and complexity is the programmers mortal enemy. For example, a derived class may poorly implement a virtual function. This may break a part of the base class that relies on the virtual function.

    Now let me be clear: I am not saying "don't use virtual functions". They are a vital and important part of C++. Just be aware of the potential for complexity.

提交回复
热议问题