Why is the virtual keyword needed?

前端 未结 4 1668
旧巷少年郎
旧巷少年郎 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.

提交回复
热议问题