I'm trying to use the factory method to return a derived class but the return type is the base class type. From my understanding I thought inheritance would allow me to do this, obviously I am wrong.
WeightExercise and CardioExercise are both derived from Exercise.
I could cast the object but I thought my design would mean I don't have to do that. Can someone point out my mistake please?
Main
ExerciseFactory ExerciseFactoryObj;
WeightExercise *WeightExerciseObj = ExerciseFactoryObj.createExercise(menuselection);
Factory Class
class ExerciseFactory
{
public:
ExerciseFactory();
~ExerciseFactory();
Exercise* createExercise(int exercisetype);
private:
static WeightExercise* createWeightExercise() { return new WeightExercise(); }
static CardioExercise* createCardioExercise() { return new CardioExercise(); }
};
Factory Implementation
Exercise* ExerciseFactory::createExercise(int exercisetype)
{
if ( 1 == exercisetype )
{
return this->createWeightExercise();
}
else if ( 2 == exercisetype )
{
return this->createCardioExercise();
}
else
{
cout << "Error: No exercise type match" << endl;
}
}
You can assign a Derived class returned from the factory to the base class one :
ExerciseFactory ExerciseFactoryObj;
Exercice *WeightExerciseObj = ExerciseFactoryObj.createExercise(menuselection);
Edited:
If you really need to access WeightExerciceObject element use :
WeightExerciceObject * weight = dynamic_cast<WeightExerciceObject *>(ExerciseFactoryObj.createExercise(menuselection));
this will return NULL if the class is not the exact one. You need to check against NULL.
In the main method, this:
WeightExercise *WeightExerciseObj = ExerciseFactoryObj.createExercise(menuselection);
should be this
Exercise *WeightExerciseObj = ExerciseFactoryObj.createExercise(menuselection);
You can't use WeightExercise, because you don't know what specific type of exercise is being returned, it might be a CardioExercise or a WeightExercise, or some other future type you aren't yet aware of.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With