I have the following situation:
I specify a pure virtual function:
virtual PredictedMatch PredictMatch(const Match &match) const = 0;
I also have:
class ImpactPredictedMatch : public PredictedMatch
Now, I wanted to do:
ImpactPredictedMatch PredictMatch(const Match &match) const;
In a class which implements the pure virtual function from earlier. I'd assumed that the compiler would simply cast the returned type as necessary, but I get:
impact_predictor.h:18:24: error: invalid covariant return type for ‘virtual ImpactPredictedMatch ImpactPredictor::PredictMatch(const Match&) const’
ImpactPredictedMatch PredictMatch(const Match &match) const;
I accept that this just doesn't work in C++, but I would really like your advice on what would be best to do instead. Do I have to return a pointer? I'd really rather not because I'd like automatic memory management, but is it the only way?
Thank you for your help!
When you return an instance of a more-derived class, the calling code can expect to store in a variable of the base type. In doing so, the result may be sliced, losing data and possibly leaking memory (at best). If you need covariant return types, your only option is a pointer or reference type. In both cases, you'll need to ensure that the object lives at least as long as the pointer/reference.
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