I want to have a class that creates different types of objects based on the string I pass. From my research, this best describes the Factory design pattern. I have success, but I ran into a design problem: I don’t know how to create objects with different length constructors.
Take, for example, an abstract parent class called Pet. Of it 3 children: fish, cat and dog. They all inherit the weight and color from Pet, so this happens in their constructors. But the fish may want a few fins and booleans as to whether it is salted fish. This is a constructor with 4 parameters. The cat would like to get the number of legs. These are 3 parameters. A dog can have parameters for its legs, breed and whether it plays well with other dogs in 5 ways.
In C ++, I understand that there is no reflection, so the most common practice is to simply declare a line map for function pointers, where the function pointer points to a function that looks something like this: / p>
template<typename T> Pet* createObject(int weight, std::string color) {return new T(weight, color);}
Again, I'm not sure how I will add more parameters to the call without affecting the calls to the constructors of other objects.
I can think of two workarounds: create new functions to accept different parameters or create default parameters for constructors above a certain size.
Workaround 1 seems excessive depending on how many different sizes of parameters I have.
Workaround 2 apparently ignores the entire constructor point, since I will have to assign data after the constructor is called.
Are there any better workarounds?
source
share