C++: “… is not a polymorphic type” while using boost::dynamic_pointer_cast

倾然丶 夕夏残阳落幕 提交于 2019-11-30 17:08:09
Nawaz

dynamic_cast works ONLY with polymorphic class. And polymorphic class is that which has atleast one virtual function, even be it the destructor.

//polymorphic classes
struct A
{
   virtual ~A(); //even virtual destructor makes a class polymorphic!
};
struct B : A
{
   void f();
};

//non-polymorphic classes    
struct C
{
   ~C(); //not virtual
};

struct D : C
{
   void f(); //not virtual either
};

In the above code, A and B are polymorphic classes, but C and D are not.

A *pA = new B();
B *pB = dynamic_cast<B*>(pA); //okay

C *pC = new D();
D *pD = dynamic_cast<D*>(pC);  //error -  not polymorphic class

Note that in dynamic_cast, only the source type need to be polymorphic in order to compile. If the destination isn't polymorphic, then dynamic_cast will return null pointer.

D *pD = dynamic_cast<D*>(pA);  //okay - source (pA) is polymorphic

if ( pD )  
      cout << "pD is not null" ;
else 
      cout << "pD is null";

Output:

pD is null

Online demo: https://web.archive.org/web/20000000000000/http://www.ideone.com/Yesxc

'dynamic_cast' : 'my_namespace::A' is not a polymorphic type because it doesn't define or inherit a single virtual function. Just add a virtual destructor and you'll be fine.

dynamic_cast works only for such 'polymorphic' types.

struct A has no virtual methods (not even a destructor), so you can't dynamic_cast from A* - only pointers to types with at least one virtual member function can be used dynamic_cast on. boost::dynamic_pointer_cast does dynamic_cast inside, to it's subject to same requirements.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!