This can get real messy as you start adding more types, I would suggest using
the factory method for doing this. Basically, use inheritance with a static
function inside of each derived type that returns an instance of itself. Then
create a map which associates a string "train", "car", etc... with the
appropriate create function. This does the same thing as the code below but
does it in a single line.
class Base { .... }
class Train : public Base {
...
static Train * create() { return new Train }
...
}
class Car : public Base {
...
static Car * create() { return new Car }
...
}
int main()
{
map funcs
You'll need a large if...else construct to do that and preferably a common superclass for the classes you want to return:
T & createObj() { vector<string> argv; ... // read T vehicle = 0;
if ( input == "plane" ) vehicle = new plane(); else if ( input == "train" ) vehicle = new train(); else if ( input == "car" ) vehicle = new car(); else { // handle input error }
return vehicle; }
-- Tom Bradley Software Engineer Jaycor / Titan Systems