Search code examples
c++classvirtual

why I changed parent virtual function arguments in child hides the father function c++?


I made a class with virtual function f() then in the derived class I rewrote it like the following f(int) why can't I access the base class function throw the child instance ?

class B{
public:
    B(){cout<<"B const, ";}
    virtual void vf2(){cout<<"b.Vf2, ";}


};
class C:public B{
public:
    C(){cout<<"C const, ";}
    void vf2(int){cout<<"c.Vf2, ";}
};

int main()
{
    C c;
    c.vf2();//error should be vf2(2)

}

Solution

  • You have to do using B::vf2 so that the function is considered during name lookup. Otherwise as soon as the compiler finds a function name that matches while traversing the inheritance tree from child -> parent -> grand parent etc etc., the traversal stops.

    class C:public B{
    public:
        using B::vf2;
        C(){cout<<"C const, ";}
        void vf2(int){cout<<"c.Vf2, ";}
    };
    

    You are encountering name hiding. Here is an explanation of why it happens ?