New C++ programmer here.
I have the following map definition:
typedef std::map<std::string, Option> MapType;
MapType my_map
Option is a unique class i created. I never actually add the Option class into my map by itself. Instead I am always adding a class that inherits from Option, for example i have a class called IntOption that store an int variable (its all it does) .
Now i have no problem adding IntOption into my map by doing:
IntOption add;
my_map.insert(std::pair<string, IntOption>("a key here", add));
This works fine because when i do a
my_map["a key here"]
it will return the value "add".
Now my question to you all good people is how can i get the subclass variable out of the return value? I can do the following
my_map["a key here"].getVariableA(); // this is in the base class Option.
but i cannot do
my_map["a key here"].getIntVariable(); //this fails because it doesnt recognize the
// getter because it is NOT in the base class but the class extending Option.
How do i fix this problem?
I have considered typedef std::map MapType;
buy i cannot figure out how to do the dynamic casting nor how to add the pointer to the class into the map.
It won't work the way you have it set up. The map is assuming that it only holds instances of Option, so it will be throwing away any IntOption data you try to send it. You will have to fall back on pointers to the options.
typedef std::map<std::string, Option*> MapType;
my_map["a key here"] = new IntOption();
IntOption *opt = dynamic_cast<IntOption*>( my_map["a key here"]);
Note that you'll have to handle memory management now, and decide when your options will be deallocated. std::auto_ptr might help with that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With