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

后端 未结 3 2020
挽巷
挽巷 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条回答
  •  醉话见心
    2020-11-28 11:43

    From 5.2.7 (Dynamic cast) :

    The result of the expression dynamic_cast(v) is the result of converting the expression v to type T.

    [ ... multiple lines which refer to other cases ... ]

    Otherwise v shall be a pointer to or an lvalue of a polymorphic type (10.3).

    From 10.3 (Virtual functions) :

    A class that declares or inherits a virtual function is called a polymorphic class.

提交回复
热议问题