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

C++C++11

C++ Problem Overview


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?)

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

You need at least a virtual function - typically, if no others are suitable, the destructor:

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

Solution 3 - C++

As your compiler says, your type A is not polymorphic. You should add a virtual function to it. For instance, a virtual destructor could be a good choice:

struct A { virtual ~A() { } };
//         ^^^^^^^ This makes A a polymorphic type

struct B : A {};

int main()
{
    A* a = new B();

    B* b = dynamic_cast<B*>(a); // Should work now
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrew TomazosView Question on Stackoverflow
Solution 1 - C++juanchopanzaView Answer on Stackoverflow
Solution 2 - C++Luchian GrigoreView Answer on Stackoverflow
Solution 3 - C++Andy ProwlView Answer on Stackoverflow