Design Tip - Avoiding an "Invalid Covariant Return Type" When Returning a Subclass

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 that implements a pure virtual function from earlier. I assumed that the compiler just applied the return type as needed, 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 agree that this just doesn’t work in C ++, but I would really like you to advise what is best done. Should I return a pointer? I would prefer not because I would like automatic memory management, but is this the only way?

Thank you for your help!

+4
source share
2 answers

, . , , , ( ). , . , /.

+4

.

name hidding:

class Base {
public:
    // Non-virtual, simply delegates to the protected virtual method.
    // May be hidden in derived class in order to covariate the return type.
    PredictedMatch predictMatch(const Match &match) const {
        return this->doPredictMatch(match);
    }

protected:
    virtual PredictedMatch doPredictMatch(const Match &match) const = 0;
};

class Derived : public Base {
public:
    // Hides Base::predictMatch()
    ImpactPredictedMatch predictMatch(const Match &match) const;

private:
    // Delegates to the specialized non-virtual member above
    PredictedMatch doPredictMatch(const Match &match) const {
        return this->predictMatch(match);  // Slices the object
    }
};

. , ​​ , .

, , , , clone(), std::unique_ptr ( , , , ).

, " " , , . , , - .

+1

All Articles