Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I have return types covariant with void*?

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()'
like image 934
user541686 Avatar asked Jun 05 '15 06:06

user541686


1 Answers

[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 function B::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 a D* and of a B& by a D& where B is an accessible base of D. 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 a D to an accessible base B, a D to an X for which D has a conversion, int* to void*, double to int, etc. We felt that the benefits from allowing such conversions through overriding would not outweigh the implementation cost and the potential for confusing users.

like image 115
T.C. Avatar answered Nov 04 '22 16:11

T.C.