Click here to Skip to main content
15,867,964 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
How can I store derived classes in a map as a value?

What I have tried:

I have tried to store derived classes in a map as a value.
Posted
Updated 8-Feb-21 5:44am
Comments
Richard MacCutchan 8-Feb-21 8:59am    
You can only store values in a map.

All C++ containers are homogeneous, i.e. they contain only one type. The best you can do for polymorphic containers (containers that store more than one type) is to store pointers to the base class in the container.

It is your responsibility to either cast the base class pointer to the appropriate pointer, or to reimplement the virtual functions provided by the base class in each of the derived classes. The latter is a better design, because it allows adding additional derived classes without rewriting any of the existing code.
 
Share this answer
 
The map has to comply to a common interface or base class, so all elements have a valid cast for it.

Somehow it shuld be possible else your design has a flaw.
 
Share this answer
 
This is the same question as How to define a map in C++ that have value as a class type?[^]. Please do not repost.
 
Share this answer
 
Comments
[no name] 8-Feb-21 9:02am    
No, sorry. This is not/never the same question!
Richard MacCutchan 8-Feb-21 9:25am    
Yes it is.
[no name] 8-Feb-21 9:29am    
After reading your linked question more carefully I see it. Sorry!
Member 15025528 8-Feb-21 23:17pm    
Hi Richard,
Thanks for your explanation.
The answers to your previous question gave you everything you need along with a link to the docs. The main thing you have to supply is a less than comparison function/functor/lambda that works with the data you have in the map.

At the site linked to previously you can find examples : std::map - cppreference.com[^].

I highly recommend that you learn how to effectively use search engines. They can be much faster and more efficient than posting questions on a message board.
 
Share this answer
 
Comments
Member 15025528 8-Feb-21 23:10pm    
Thanks for suggestion Rick.
I have tried for this. But for some confusion, posted the question.
Member 15025528 8-Feb-21 23:24pm    
Thanks Rick.
Well explained, understood.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900