I want to instantiate a base class pointer to point to a newly constructed derived class object. The actual class for the object will change depending on the application type, so I want to use a Factory method to switch on certain variables in order to construct the right object.
However I don’t want to have to do the switch each time. In fact, once the application starts, the type of object I want to create in this situation will always be the same – so actually I only need to do this switch only once.
Can I pass in a derived class Constructor to the function creating the object?
For example:
typedef DerivedObject (*DerivedClassConstructor)( void );
class ContainingClass:
{
public:
ContainingClass ( DerivedClassConstructor * f )
{
baseptr = f();
}
BaseClass * baseptr
};
Is there a better design?
I think that’s pretty sane. Just pass a function object and save it since it seems you need to recall it later (otherwise why not pass the pointer directly and create the object before?)