std::map unable to handle polymorphism?

前端 未结 5 664
时光说笑
时光说笑 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-19 00:07

    Its case of Object Slicing. Try to insert with pointers.

    In the presence of inheritance copying leads to slicing. That is, if you create a map of base class objects and you try to insert derived class objects into it, the derivedness of the objects will be removed as the objects are copied (via the base class copy constructor) into the map.

    Hence, it is recommended to use pointers rather than copies itself.

提交回复
热议问题