Return value of an overridden class

Hello guys,

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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... could anyone please exaplain to what extent this is legal?
Last edited on
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:
virtual double 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class MyBaseClass
{
	int value;

public:
	virtual MyBaseClass* getValue() = 0;
};

class MyClass : public MyBaseClass
{
	double value;

public:
	virtual MyClass* getValue() override;
};

MyClass* MyClass::getValue()
{
	return 0;
}
It complained when I created an object of the class. Thank you :-)
Topic archived. No new replies allowed.