Returning object by a class name

I was hoping to have a method that could return a object of class.

I have classes Class1, Class2 and Class3, which are derived from base class named as BaseClass, and then I have a class manager named as Manager with a method create(string). Is it possible to return an instance from Manager of classes Class1, Class2 or Class3 by invoking method create?

Example:
1
2
Manager m = Manager();
Class1 class1 = m.create("Class1");
Reflection isn't easy to do in C++. Are you sure you need to use it?
I think your manager class is going to have to know all the types.

You might do something like this:

1
2
3
4
5
6
7
BaseClass* Manager::create(const std::string& type)
{
    if(type == "Class1") return new Class1;
    if(type == "Class2") return new Class2;
    // ... etc
    return 0;
}


It could be more efficient by passing some kind of enumeration rather than a string.
Last edited on
Topic archived. No new replies allowed.