In the trivial example inheritance hierarchy:
class Food
{
virtual ~Food();
};
class Fruit : public Food
{
virtual ~Fruit();
};
class Apple: public Fruit
{
virtual ~Apple();
}
class Vegetable: public Food
{
virtual ~Vegetable();
}
I wish to create a method that can clone an object from its subclass or baseclass instance:
Apple* apple1 = new Apple();
Apple* clone1 = apple1->clone();
Food* food1 = apple1;
Apple* clone2 = food1->clone();
I see a few possible solutions to the problem:
Use polymorphism to create a virtual function that is explicitly defined for each subclass.
Use a templated factory method to take an instance of a class and the type of the subclass to create the new instance.
Register an id with each class and subclass that is stored elsewhere to lookup which subclass to create on calling a baseclass clone function.
None of these seem ideal, but I'm leaning more towards the third solution as it simplifies calling the clone function without requiring a definition to be written for every subclasses (for which there will be a lot).
However, I'm very much open to any suggestions, are there better ways of doing this?