Search code examples
c++overloadingoverload-resolution

Private virtual function of base is hidden by private virtual function of derived


The following code

class A
{
public:
    void g(int x)
    {
        f(x);
    }

protected:
    virtual void f(int) = 0;
};

class B: public A
{
protected:
    virtual void f(float) = 0;

private:
    void f(int x) override final
    {
        f(float(x));
    }
};

class C: public B
{
private:
    void f(float) override final {}
};

int
main()
{
    C c;
    c.g(1);

    return 0;
}

compiled with g++ -Woverloaded-virtual produces said warning:

x.cc:19:7: warning: ‘virtual void B::f(int)’ was hidden [-Woverloaded-virtual]
  void f(int x) override final
       ^
x.cc:28:7: warning:   by ‘virtual void C::f(float)’ [-Woverloaded-virtual]
  void f(float) override final {}
       ^

I do not understand what is being hidden here. From the scope of C there is only one possible overload to f as B::f(int) is private within C.

From the scope of B there are two, but both are explicitly named inside B.


Solution

  • The warning is telling you that the function C::f(float) hides B::f(int), and that's because it does. Access specifiers don't affect overloading, so the fact that B::f(int) is private doesn't matter. Even if B::f(int) was public, it wouldn't be considered for overload resolution, and that's what "hiding" refers to.