dynamic_cast Error: source type is not polymorphic

#include
 using namespace std;
 class C{
   public:
   virtual ~C(){}A dummy function must be added, otherwise the following error will be reported, the
 };
 class A:public C{
 };
 class B:public C{
 };
int main(){
C* pa=new A();
B* pb=dynamic_cast<B*>(pa);
if(pb)
cout<<"success!";
else
cout<<"fail!";

}

[Error] cannot dynamic_cast’pa’ (of type’class C*’) to type’class B*’ (source type is not polymorphic)

1. The base class pointer pa points to the subclass object. Class A and Class B are actually irrelevant, so two unrelated classes do dynamic_cast, pb is null, so the final operation result is: fail!

2. Dynamic conversion classes need to add a virtual function. Any virtual function can be used.

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *