dynamic_cast vs exposing virtual functions in parent class (C++)

删除回忆录丶 提交于 2019-12-20 01:45:12

问题


I have a parent class "base" and another class "derived" that inherits from "base".

"derived" has 1 method cH1.

if I do this:

base* b = new derived();

And I want to be able to do this:

b->cH1();

Obviously I can't and there are 2 solutions:

  • Either declare cH1 as pure virtual in base.
  • or do this:

    dynamic_cast<derived*>(b)->cH1();
    

Which one is a better practice?


回答1:


If cH1 method semantically applies to base, then make it a base's method. Else, leave cH1 to derived, and use dynamic_cast. I think the semantics of your classes should drive your choice.

For example, if you have a base class Vehicle and derived classes Car, Motorbike, and Aircraft, a method like TakeOff() has a semantics compatible with Aircraft but not with Car or Motorbike, so you may want to make TakeOff() an Aircraft method, not a Vehicle method.




回答2:


First, in order to use dynamic_cast, base must have at least one virtual function.

Second, use of dynamic_cast is usually a sign of a design mistake. If derived is truly a child of base, then a derived object should be able to stand in wherever a base object is expected, and that usually means that base has virtual functions, either pure virtual or not, and that derived overrides some or all of them.

Without knowing what cH1 does, though, it's impossible to recommend an approach.




回答3:


dynamic_cast is cleaner and more flexible, but a bit slower.

Remember when you use dynamic_cast to check the returned pointer for NULL.



来源:https://stackoverflow.com/questions/12427562/dynamic-cast-vs-exposing-virtual-functions-in-parent-class-c

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