Conflict type return from base class with derived class using auto

I have the following code:

struct A{}; struct Base { virtual A& internal() = 0; }; struct Derives : public Base { auto& internal() override { // <-- conflicting return type return internal_; } private: A internal_; }; int main() { Derives d; auto& internal = d.internal(); } 

This is not compiled (tested on coliru - with gcc) with a conflicting return type - my question is why the compiler cannot determine that both internal_ (and therefore return type) A ? Is the type deduced for auto at a different compilation stage, for example, than the one that checks for virtual overrides? Of course, this compiles if you replace auto with the correct type, but that does not apply to the point.

(Here is the clang error, gcc is somewhat similar)

main.cpp: 8: 11: error: the return type of the virtual function is "internal" not covariant with the return type of the function that it overrides ('auto & amp; "is not inferred from" A & ")

 auto& internal() override { // <-- conflicting return type ~~~~~ ^ 

main.cpp: 4: 16: note: overridden virtual function here

 virtual A& internal() = 0; ~~ ^ 

1 error generated.

+8
c ++ c ++ 14
source share
1 answer

From [dcl.spec.auto] :

A function declared with a return type that uses a placeholder type is not virtual ([class.virtual]).

internal() is a virtual function, so you cannot use auto .

The initial sentence points to this:

It would be possible to enable inference of return type for virtual functions, but this would complicate both the redefinition check and the vtable location, therefore it is preferable to disable this.

+14
source share

All Articles