Let\'s say I have a class box, and a user can create boxes. How to do it? I understand I create objects by className objectName(args);
but how
The following factory method creates Box
instances dynamically based on user input:
class BoxFactory
{
public:
static Box *newBox(const std::string &description)
{
if (description == "pretty big box")
return new PrettyBigBox;
if (description == "small box")
return new SmallBox;
return 0;
}
};
Of course, PrettyBigBox
and SmallBox
both derive from Box
. Have a look at the creational patterns in the C++ design patterns wikibook, as one of them probably applies to your problem.