In C++, should I almost always use virtual inheritance?

牧云@^-^@ 提交于 2019-11-27 03:04:57

问题


I see from this entry that virtual inheritance adds sizeof(pointer) to an object's memory footprint. Other than that, are there any drawbacks to me just using virtual inheritance by default, and conventional inheritance only when needed? It seems like it'd lead to more future-proof class design, but maybe I'm missing some pitfall.


回答1:


The drawbacks are that

  1. All classes will have to initialize all its virtual bases all the time (e.g. if A is virtual base of B, and C derives from B, it also have to initialize A itself).
  2. You have to use more expensive dynamic_cast everywhere you use a static_cast (may or may not be the issue, depending on your system and whether your design requires it).

Point 1 alone makes it not worth it, since you can't hide your virtual bases. There is almost always a better way.




回答2:


In my experience, virtual inheritance (as opposed to virtual methods) is almost never needed. In C++ it's used to address the "diamond inheritance problem", which if you avoid multiple inheritance cannot actually happen.

I'm pretty sure that I've never encountered virtual inheritance outside C++ books, which includes both code I write and million+ line systems I maintain.



来源:https://stackoverflow.com/questions/4543537/in-c-should-i-almost-always-use-virtual-inheritance

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