dynamic_cast is failing when casting from base to child class

373 views Asked by At

I have a struct

struct foo : public std::map<std::string, int>
{
};

and a child struct;

struct bar : public foo
{
    int another_member;
}

But I can't use bar* b = dynamic_cast<bar*>(f) where f is a pointer to a foo.

Even if I refactor foo to

struct foo
{
     std::map<std::string, int> m;
};

I still have the problem. I've played around with my RTTI settings to no avail. What on earth is going on?

The error is:

error C2683: 'dynamic_cast' : 'Credit::WaterfallSimulationResult' is not a polymorphic type

1

There are 1 answers

0
Bathsheba On BEST ANSWER

dynamic_cast will only work on polymorphic types, that is structs or classes that have a virtual function table.

The best thing to do is to introduce a virtual function into your base struct, and the best function to introduce is the virtual destructor, which is arguably a good thing to do anyway:

struct foo
{
     std::map<std::string, int> m;
     virtual ~foo(){};
};

Note that this forces you to use your "refactored" form of foo: STL containers are not designed to be used as base classes.