c++ - Design advice -- avoiding "invalid covariant return type" when returning subclass -
i have following situation:
i specify pure virtual function:
virtual predictedmatch predictmatch(const match &match) const = 0;
i have:
class impactpredictedmatch : public predictedmatch
now, wanted do:
impactpredictedmatch predictmatch(const match &match) const;
in class implements pure virtual function earlier. i'd assumed compiler cast returned type necessary, get:
impact_predictor.h:18:24: error: invalid covariant return type ‘virtual impactpredictedmatch impactpredictor::predictmatch(const match&) const’ impactpredictedmatch predictmatch(const match &match) const;
i accept doesn't work in c++, advice on best instead. have return pointer? i'd rather not because i'd automatic memory management, way?
thank help!
when return instance of more-derived class, calling code can expect store in variable of base type. in doing so, result may sliced, losing data , possibly leaking memory (at best). if need covariant return types, option pointer or reference type. in both cases, you'll need ensure object lives @ least long pointer/reference.
Comments
Post a Comment