dynamic_cast vs exposing virtual functions in pare

2020-04-10 01:58发布

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?

3条回答
贼婆χ
2楼-- · 2020-04-10 02:21

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.

查看更多
Emotional °昔
3楼-- · 2020-04-10 02:42

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.

查看更多
唯我独甜
4楼-- · 2020-04-10 02:44

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

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

查看更多
登录 后发表回答