Virtual methods with deduced return type in G++

Viewed 78

There is a nice question explaining why virtual functions cannot use return type deduction: Why can't virtual functions use return type deduction?

Surprisingly it appears that GCC allows such possibility (as a language extension). For example, this program is accepted by GCC:

#include <iostream>

struct A {
    virtual auto f() -> auto { return 1; }
};

struct B: A {
    virtual auto f() -> auto override { return 2.5; }
};

int main() {
    B b;
    A & a = b;
    std::cout << b.A::f() << ' ' << b.f() << ' ' << a.f();
}

Demo: https://gcc.godbolt.org/z/n3ejPshe7

I guess that GCC is wrong here at least with pedantic flags -std=c++20 -Wall -Wextra -pedantic-errors where all extensions must be turned off.

But the question is about the program output, which is 1 2.5 0. Since expressions a.f() and b.f() are evaluated to distinct values then struct B actually has two different virtual functions despite of override keyword, which looks as a bug.

0 Answers
Related