What is the advantage of using dynamic_cast instead of conventional polymorphism?

前端 未结 5 1865
青春惊慌失措
青春惊慌失措 2020-12-18 04:19

We can use Polymorphism (inheritance + virtual functions) in order to generalize different types under a common base-type, and then refer to different objects as if they wer

5条回答
  •  轮回少年
    2020-12-18 05:05

    It allows you to do things which you can only do to the derived type. But this is usually a hint that a redesign is in order.

    struct Foo
    {
      virtual ~Foo() {}
    };
    
    struct Bar : Foo
    {
      void bar() const {}
    };
    
    int main()
    {
      Foo * f = new Bar();
      Bar* b = dynamic_cast(f);
      if (b) b->bar(); 
      delete f;
    }
    

提交回复
热议问题