FAQ: Why does dynamic_cast only work if a class has at least 1 virtual method?

后端 未结 3 2022
挽巷
挽巷 2020-11-28 11:36

This does not compile in C++:

class A
{
};

class B : public A
{
};

...

A *a = new B();
B *b = dynamic_cast(a);
3条回答
  •  旧时难觅i
    2020-11-28 11:43

    Because dynamic_cast can only downcast polymorphic types, so sayeth the Standard.

    You can make your class polymoprphic by adding a virtual destructor to the base class. In fact, you probably should anyway (See Footnote). Else if you try to delete a B object through an A pointer, you'll evoke Undefined Behavior.

    class A
    {
    public:
      virtual ~A() {};
    };
    

    et voila!

    Footnote

    There are exceptions to the "rule" about needing a virtual destructor in polymorphic types.
    One such exception is when using boost::shared_ptr as pointed out by Steve Jessop in the comments below. For more information about when you need a virtual destructor, read this Herb Sutter article.

提交回复
热议问题