Why should virtual functions not be used excessively?

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

    I suspect you misunderstood the statement.

    Excessively is a very subjective term, I think that in this case it meant "when you don't need it", not that you should avoid it when it can be useful.

    In my experience, some students, when they learn about virtual functions and get burned the first time by forgetting to make a function virtual, think that it is prudent to simply make every function virtual.

    Since virtual functions do incur a cost on every method invocation (which in C++ cannot usually be avoided because of separate compilation), you are essentially paying now for every method call and also preventing inlining. Many instructors discourage students from doing this, though the term "excessive" is a very poor choice.

    In Java, a "virtual" behavior (dynamic dispatching) is the default. However, The JVM can optimize things on the fly, and could theoretically eliminate some of the virtual calls when the target identity is clear. In additional, final methods or methods in final classes can often be resolved to a single target as well at compile time.

提交回复
热议问题