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:
virtualint getValue() = 0;
}
class MyClass : public MyBaseClass
{
double value;
public:
virtualdouble getValue(); // here!!! return is double, not int
}
double MyClass::getValue()
{
returnthis->value;
}
The compiler totally accepted something similar... could anyone please exaplain to what extent this is legal?
Is is legal in some case but not here(you don't override getValue at all) and i'm surprised your compiler don't even generate a warning.... .
Here you are simply redefining getValue in MyClass, this mean getValue is not overriden and MyClass is still abstract(you can't instanciate it).
What compiler do you use? If it support the override keyword from C++11 I strongly advise you to use it after methods overrides like this: virtualdouble getValue() override;
This way you have an error if you are trying to badly override a virtual method.
It is legal in case the return types are covariants: the overriden method return a pointer or reference to a type which derive from the type returned(also pointer or reference) by the original method. For example this example is valid: