Why is the virtual keyword needed?

前端 未结 4 1669
旧巷少年郎
旧巷少年郎 2021-01-13 07:17

In other words, why doesn\'t the compiler just \"know\" that if the definition of a function is changed in a derived class, and a pointer to dynamically allocated memory of

相关标签:
4条回答
  • 2021-01-13 07:25

    virtual keyword tells the compiler to implement dynamic dispatch.That is how the language was designed. Without such an keyword the compiler would not know whether or not to implement dynamic dispatch.

    The downside of virtual or dynamic dispatch in general is that,

    • It has slight performance penalty. Most compilers would implement dynamic dispatch using vtable and vptr mechanism, where the appropriate function to call is decided through vtable and hence an additional indirection is needed in case of dynamic dispatch.
    • It makes your class Non-POD.
    0 讨论(0)
  • 2021-01-13 07:29

    The compiler doesn't know, because it can't. It might be your intention, to not use virtual functions, because there's always a cost associated with every feature.

    0 讨论(0)
  • 2021-01-13 07:38

    One of the main designing principles of C++ is that C++ does not incur overhead for features that are not used (the "zero-overhead principle"). This is because of a focus on high performance

    This is why you need to opt in to features like virtual functions while in languages like Java, functions are virtual by default.

    0 讨论(0)
  • 2021-01-13 07:47

    One reason:

    Consider base classes located in separate module, like library.

    And derived classes in your application.

    How would compiler knows during compiling the library that the given function is/must be virtual.

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