I need to write a function which could create any type object. It receives class name as parameter.
If classes are similar, we can derive all those classes from a single base class and let function return Base *. User of the function could use runtime polymorphism to use the returned object. In this case, function looks like below.
Base* createObject(string objName)
{
if(objName == "D1")
return new D1;
else if(objName == "D2")
return new D2;
return NULL;
}
If the classes are dissimilar, they can’t be inherited from a single base class as it would not be proper inheritance. In this case, above function would not be useful.
Lets say i have 3 dissimilar classes like Helicopter, Kitchen and College.
In this case, how does single function could create any kind of object ?
I have one solution like below.
Use a wrapper class to wrap all dissimilar class pointers in an Union.
Then let function create Wrapper object and fill appropriate class pointer based on classname passed to it.
That functin looks like below
Wrapper* createObject(string objType)
{
Wrapper *pWrapper = new Wrapper();
pWrapper->objectType = objType;
if(objType == "Helicopter")
{
pWrapper->pHelicopter = new Helicopter;
}
else if(objType == "Kitchen")
{
pWrapper->pKitchen = new Kitchen;
}
else if(objType == "College")
{
pWrapper->pCollege = new College();
}
return pWrapper;
}
Wrapper class looks like below.
class Wrapper
{
public:
string objectType;
union
{
Helicopter *pHelicopter;
Kitchen *pKitchen;
College *pCollege;
};
};
Is there any better solution than above ?
Boost already has 2 possible solutions to your problem: Boost.Variant and Boost.Any.
But preferably you should avoid such a design in the first place if you can. If one function returns unrelated objects and you can’t refactor to give the types a common interface, you should probably split it into multiple functions.