Possible Duplicate:
c++ virtual function return type
I have a simple but confusing question here. Is it legal to have a different return value type for overridden methods than the abstact ones defined in the base class?? I did that and the compiler didn’t complain… could someone please explain?
class MyBaseClass
{
int value;
public:
virtual int getValue() = 0;
};
class MyClass : public MyBaseClass
{
double value;
public:
virtual double getValue(); // here!!! return is double, not int
};
double MyClass::getValue()
{
return this->value;
}
The compiler totally accepted something similar (MSVC und MinGW)… could anyone please exaplain to what extent this is legal?
The return type is allowed to differ but only in a bery restrictive way and you code is illegal. The only way the return type of an override is allowed to differ is that can be covariant if yhe return type of the base is a pointer or a reference. Put differently: if the base returns a pointer or a reference to a base class the overrude is allowed to return a pointer or a reference, respectively, to a class derived of the base.