I have a class with many derived types, and I have a unique number associated with each derived class. Is there a simple way to match a number with a derived type?
Some pseudo code:
class foo{
public:
virtual int bar(int) = 0;
}
class fan:foo{
public:
int bar(int num){ return num * 5; )
}
class fawn:foo{
public:
int bar(int num){ return num * 9; );
}
int main(){
vector<foo*> obj;
for( int i = 0; i < 100; i ++ ){
int num = rand() % 2;
if( num == 0 )
obj.push_back( new fan() );
if( num == 1 )
obj.push_back( new fawn() );
}
}
This does what I want, but I have many more than two classes, and I plan to add many more. Is there any way to do this in a less verbose manner?
I’m using MinGW, if it matters at all.
What you probably want is the factory pattern. Basically, you’ll make something like this:
There is no way to get rid of the enumeration, but at least this way you’ll have to construct it exactly once and then you can use it everywhere
foois visible.Edit: Personally I like the above style but a more compact version is