Reputation: 49
I'm trying to create a base class with a derived type; where in the base class I have a pure virtual method that returns something of the type DtBase (another class), and when overriding it in the derived class returns something of the type DtDerived (which derives from DtBase). I get an error saying that the type of the return is not identical nor covariant with the type of the overriden pure virtual function. I don't understand why does this happen, are DtBase and DtDerived not covariant?
Below is a code that presents this error:
//DtBase.h
class DtBase{
public:
DtBase();
virtual ~DtBase();
};
class DtDerived: public DtBase{
public:
DtDerived();
~DtDerived();
};
//Base.h
#include "DtBase.h"
class base{
public:
base();
virtual DtBase foo()=0;
virtual ~base();
};
class derived: public base{
public:
derived();
DtDerived foo(); // This is where I get the error
~derived();
};
Upvotes: 2
Views: 46
Reputation: 15164
You need to return a DtBase pointer DtBase::foo() and DtDerived pointer in DtDerived::foo(), otherwise the DtDerived portion would simply get sliced off and the caller would never see that it was actually a DtDerived that was returned.
Upvotes: 2