Invalid conversion from BaseClass* to DerivedClass*

c++, c++11, inheritance

Solution

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.

Problem

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; } } ```

Original source