Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design advice -- avoiding "invalid covariant return type" when returning subclass

Tags:

c++

c++11

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!

like image 595
noctilux Avatar asked Jul 14 '15 11:07

noctilux


1 Answers

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.

like image 55
Toby Speight Avatar answered Sep 30 '22 16:09

Toby Speight