Virtual function implemented in base class not being found by compiler

后端 未结 2 610
傲寒
傲寒 2021-01-01 15:19

I\'ve got a situation where it seems like the compiler isn\'t finding the base class definition/implementation of a virtual function with the same name as another member fun

相关标签:
2条回答
  • 2021-01-01 15:51

    You hide func(One&) function in Derived. You could use fully qualified name:

    d.Base::func( one );
    
    0 讨论(0)
  • 2021-01-01 16:06

    You are hiding the method in the derived class. The simplest solution is to add a using declaration to the derived class.

    struct Derived : public Base
    {
        using Base::func;
        virtual void func( Two & );
    };
    

    The issue is that when the compiler tries to lookup the func identifier in the call d.func(one) it has to do that from Derived upwards, but it will stop in the first context where it finds the func identifier, which in this case it is Derived::func. No further lookup is performed and the compiler was seeing only the Derived::func( Two& ).

    By adding the using Base::func; directive, when the compiler sees the Derived definition it brings all of Base::func declarations into scope, and it will find that there is a Base::func( One & ) that was not overridden in Derived.

    Note also that if you were calling through a reference to Base, then the compiler would find both overloads of func and would dispatch appropriately each one to the final overrider.

    Derived d;
    Base & b = d;
    b.func( one ); // ok even without the 'using Base::func;' directive
    
    0 讨论(0)
提交回复
热议问题