compiler errors - C++: "... is not a polymorphic type" while using boost::dynamic_pointer_cast -


why receive following error following code?

1>c:\libs\boost_1_44\boost/smart_ptr/shared_ptr.hpp(259): error c2683: 'dynamic_cast' : 'my_namespace::a' not polymorphic type 1>          d:\[location]\[header_filename].h(35) : see declaration of 'my_namespace::a' 1>          c:\libs\boost_1_44\boost/smart_ptr/shared_ptr.hpp(522) : see reference function template instantiation 'boost::shared_ptr<t>::shared_ptr<my_namespace::a>(const boost::shared_ptr<my_namespace::a> &,boost::detail::dynamic_cast_tag)' being compiled 1>          1>          [ 1>              t=my_namespace::b 1>          ] 1>          [location]\[source_filename].cpp(217) : see reference function template instantiation 'boost::shared_ptr<t> boost::dynamic_pointer_cast<my_namespace::b,striker::a>(const boost::shared_ptr<my_namespace::a> &)' being compiled 1>          1>          [ 1>              t=my_namespace::b 1>          ] 1>c:\libs\boost_1_44\boost/smart_ptr/shared_ptr.hpp(260): fatal error c1903: unable recover previous error(s); stopping compilation 

the c++ code more or less following:

#include <list> #include "boost/pointer_cast.hpp" #include "boost/shared_ptr.hpp"  struct { public:     a(const myenum an_enum_, const int an_int_) :         an_enum(an_enum_),         an_int(an_int_)     {}      const myenum an_enum;     const int an_int; };  struct b : public { public:     b(const int some_int_, const mystruct &a_struct_) :         a(enum_option_a, an_int_),         a_struct(a_struct_)     {}      const mystruct a_struct; };   // ussage in function: // ... boost::shared_ptr<a> a_ptr = boost::shared_ptr<a>( new b() ); std::list<boost::shared_ptr<a>> a_list; a_list.push_back(a_ptr); // ... boost::shared_ptr<a> a_ptr2 = a_list.front(); boost::shared_ptr<b> b_ptr = boost::dynamic_pointer_cast<b>(a_ptr2); // <-- error here // ... 

dynamic_cast works polymorphic class. , polymorphic class has atleast 1 virtual function, destructor.

//polymorphic classes struct {    virtual ~a(); //even virtual destructor makes class polymorphic! }; struct b : {    void f(); };  //non-polymorphic classes     struct c {    ~c(); //not virtual };  struct d : c {    void f(); //not virtual either }; 

in above code, a , b polymorphic classes, c , d 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 in dynamic_cast, source type need polymorphic in order compile. if destination isn't polymorphic, dynamic_cast return null pointer.

d *pd = dynamic_cast<d*>(pa);  //okay - source (pa) polymorphic  if ( pd )         cout << "pd not null" ; else        cout << "pd null"; 

output:

pd null 

online demo : http://www.ideone.com/yesxc


Comments