This question already has an answer here:
Store derived class objects in base class variables
4 answers
I have a base class with 3 different inherited classes. I want to add all the inherited classes to a vector and at a later point when I need to iterate through the inherited classes and call functions in them.
The order each inherited class is added to the vector is random, based on a file input from the user.
Here is what I have:
static std::vector<Base> List;
Inh1 inh1;
Inh2 inh2;
Inh3 inh3;
Base &intf = inh1;
List.push_back(intf);
... similarly for the other 2
When I read them:
for (long index=0; index<(long)List.size(); ++index) {
if (!(List.at(index).Works())) {
printf ("Works");
}
...
}
The .Works() calls the virtual method inside the base class and not the inh1 class. I'm not sure how to make it work. I can't static/dynamic cast it when I want to access it because I don't know which one it is I'm accessing....Any ideas?
Thanks
Aucun commentaire:
Enregistrer un commentaire