I’m trying to create a structure array which links input strings to classes as follows:
struct {string command; CommandPath cPath;} cPathLookup[] = {
{"set an alarm", AlarmCommandPath},
{"send an email", EmailCommandPath},
{"", NULL}
};
which will be used as follows:
CommandPath *cPath = NULL;
string input;
getline(cin, input);
for(int i = 0; cPathLookup[i] != ""; i++) {
if(cPathLookup[i].command == input)
cPath = new cPathLookup[i].cPath;
}
Obviously, this code is meaningless, but I think my intention is apparent – depending on input, I’d like cPath to be initialized as either a new AlarmCommandPath or a new EmailCommandPath. I could handle it with a function returning an instance depending on input, but a whole sequence of ifs just seems inelegant.
I should also note that, in case it’s not apparent and important, that AlarmCommandPath and EmailCommandPath are derived from CommandPath, and CommandPath is an abstract class.
Thanks for any help you can offer.
EDIT: I just noticed that, in spite of CommandPath being abstract, I have a declaration:
CommandPath *cPath = NULL;
in working code. Why does that compile?
AlarmCommandPath and EmailCommandPath are derived from COmmandPath, correct?
In this case you cannot assign an instance of AlarmCommandPath/EmailCommandPath to CommandPath – it is technically possible, but it won’t do what you want. The instance
CommandPath will remain an instance of CommandPath (it will have virtual function table of CommandPath), no matter what you assign to it.
You need to use factory methods (a function that will return CommandPath*). Something like that: