Why is the virtual keyword needed?

佐手、 提交于 2019-12-19 07:34:34

问题


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 that derived class calls the changed function, then that function in particular should be called and not the base class's?

In what instances would not having the virtual keyword work to a programmer's benefit?


回答1:


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.



回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/13600934/why-is-the-virtual-keyword-needed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!