Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "source type is not polymorphic" when trying to use dynamic_cast

Tags:

c++

c++11

struct A {};  struct B : A {};  int main() {     A* a = new B();      B* b = dynamic_cast<B*>(a); } 

gives:

cannot dynamic_cast 'a' (of type 'struct A*') to type 'struct B*' (source type is not polymorphic)

How can I make A polymorphic? I want to safely cast it to B.

(One way is to add a dummy virtual function, but is there a better way?)

like image 404
Andrew Tomazos Avatar asked Feb 27 '13 14:02

Andrew Tomazos


1 Answers

You need to make A polymorphic, which you can do by adding a virtual destructor or any virtual function:

struct A {   virtual ~A() = default; }; 

or, before C++11,

struct A {   virtual ~A() {} }; 

Note that a polymorphic type should have a virtual destructor anyway, if you intend to safely call delete on instances of a derived type via a pointer to the base.

like image 50
juanchopanza Avatar answered Sep 30 '22 01:09

juanchopanza