c++ - Cannot dynamic cast when using dynamic_pointer_cast -


why code not work?

std::shared_ptr<event> e = ep->pop(); std::shared_ptr<trackerevent> t;  t = std::dynamic_pointer_cast<trackerevent>(e); 

i following error:

/usr/include/c++/4.6/bits/shared_ptr.h:386: error: cannot dynamic_cast '(& __r)->std::shared_ptr<event>::<anonymous>.std::__shared_ptr<_tp, _lp>::get [with _tp = event, __gnu_cxx::_lock_policy _lp = (__gnu_cxx::_lock_policy)2u]()' (of type 'class event*') type 'class trackerevent*' (source type not polymorphic) 

trackerevent inherits event guess problem can't cast in direction. ep->pop() might either return object of type event or trackerevent. , hoping when try cast trackerevent , returns null know whether have event or trackerevent...

how that?

the compiler telling going on @ end of message:

(source type not polymorphic)

your event base class needs have @ least 1 virtual member function (i.e. polymorphic type) in order allow dynamic casts. make destructor of event virtual:

class event { public:     virtual ~event() { /* whatever goes here, or nothing... */ }     // ... }; 

here live example polymorphic types, showing code compiles (removing virtual destructor cause compilation error similar 1 seeing).

as correctly mentioned luc danton in comments, defaulted version of virtual destructor can defined way (if compiler c++11-compliant in respect):

class event { public:     virtual ~event() = default;     // ... }; 

Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -