std::map unable to handle polymorphism?

前端 未结 5 659
时光说笑
时光说笑 2021-01-18 23:38

When using std::map in c++, is it possible to store inherited classes as their \"base class\" in the map and still being able to call their overloaded methods? See this exam

5条回答
  •  遇见更好的自我
    2021-01-18 23:58

    Polymorphism doesn't work in that case because the std::map stores the Base as a value type, so the objects get sliced.

    If you want to have polymorphism on stored objects, you need to store pointers or use one of the boost ptr containers to effect the same. This means you need to remember to delete the memory afterwards (please don't put pointers to stack objects into the map)

提交回复
热议问题