Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid conversion from BaseClass* to DerivedClass*

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;
}
}
like image 621
Martin Weston Avatar asked Dec 11 '25 13:12

Martin Weston


2 Answers

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.

like image 63
MBen Avatar answered Dec 13 '25 01:12

MBen


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.

like image 35
Scott Langham Avatar answered Dec 13 '25 01:12

Scott Langham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!