Why is the following code a covariance error? Isn't T *
covariant with void *
...?
struct Base { virtual void *foo(); };
struct Derived : Base { int *foo(); };
GCC says:
invalid covariant return type for 'virtual int* Derived::foo()'
[class.virtual]/p7, emphasis mine:
The return type of an overriding function shall be either identical to the return type of the overridden function or covariant with the classes of the functions. If a function
D::f
overrides a functionB::f
, the return types of the functions are covariant if they satisfy the following criteria:
- both are pointers to classes, both are lvalue references to classes, or both are rvalue references to classes [footnote omitted]
- [...]
From pages 294-5 of D&E:
Afer some consideration of the alternatives, we decided to allow overriding of a
B*
by aD*
and of aB&
by aD&
whereB
is an accessible base ofD
. In addition,const
can be added or subtracted wherever that is safe. We decided not to relax the rules to allow technically feasible conversions such as aD
to an accessible baseB
, aD
to anX
for whichD
has a conversion,int*
tovoid*
,double
toint
, etc. We felt that the benefits from allowing such conversions through overriding would not outweigh the implementation cost and the potential for confusing users.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With