I have an ABC with several derived classes. To create these derived classes I use the factory pattern:
.h file:
class derivedFactory { public: base* createInstance(); };
.cpp file:
base* derivedFactory::createInstance() { return new derived(); }
Is there any advantage to this over just having a free function:
.h file:
base* derivedFactoryFunction();
.cpp file:
base* derivedFactoryFunction() { return new derived(); }
Also: I use the abstract factory pattern for dependency injection. I might use an inheritance hierarchy based on the ABC:
class objectCreator { public: base* create() = 0; };
Is there any advantage to using this over a function pointer:
boost::function<base* ()> factory_ptr;
Using boost::bind/lambda this seems to make my code more composable, and if I wish I can wrap a real factory object in it. I can see that there may be a slight performance decrease but this is much to worry about as it is only called during startup.
It depends on how flexible your factory needs to be. If the factory needs external information (like from a configuration file, program options, etc) to determine how to construct objects, than an object makes sense. If all you will ever need is in the arguments to factory, than a function is probably fine.
The only advantage I can see to having a pointer is for testing, where you can use a different factory function.