C++: rationale behind hiding rule

前端 未结 5 1002
旧时难觅i
旧时难觅i 2020-11-27 20:15

What\'s the rationale behind the hiding rule in C++?

class A { void f(int); }
class B : public A { void f(double); } // B::f(int) is hidden
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 20:56

    Another reason for hiding base class's member function (with same name but different signatures) might be due to ambiguity caused by optional parameters. Consider the following example:

    #include 
    
    class A
    {
    public:
        int foo(int a, int b=0)
        {
            printf("in A : %d, %d\n", a, b);
        }
    };
    
    class B : public A
    {
    public:
        int foo(int a)
        {
            printf("in B : %d\n", a);
            foo(a); //B:foo(a) will be called unless we explicitly call A:foo(a)
            foo(a, 1); // compile error: no matching function for call to B:foo(int&, int)
        }
    };
    
    
    int main()
    {
        B b;
        b.foo(10);
        return 0;
    }
    

    If the foo method in base class hadn't become hidden, it wouldn't be possible for compiler to decide whether A::foo should be called or B::foo since the following line matches both signatures:

    foo(a);
    

提交回复
热议问题