Why is a public const method not called when the non-const one is private?

前端 未结 11 1171
天涯浪人
天涯浪人 2020-12-25 09:18

Consider this code:

struct A
{
    void foo() const
    {
        std::cout << \"const\" << std::endl;
    }

    private:

        void foo()
           


        
11条回答
  •  北荒
    北荒 (楼主)
    2020-12-25 09:40

    Suppose access control came before overload resolution. Effectively, this would mean that public/protected/private controlled visibility rather than accessibility.

    Section 2.10 of Design and Evolution of C++ by Stroustrup has a passage on this where he discusses the following example

    int a; // global a
    
    class X {
    private:
        int a; // member X::a
    };
    
    class XX : public X {
        void f() { a = 1; } // which a?
    };
    

    Stroustrup mentions that a benefit of the current rules (visibility before accessibility) is that (temporarily) chaning the private inside class X into public (e.g. for the purposes of debugging) is that there is no quiet change in the meaning of the above program (i.e. X::a is attempted to be accessed in both cases, which gives an access error in the above example). If public/protected/private would control visibility, the meaning of the program would change (global a would be called with private, otherwise X::a).

    He then states that he does not recall whether it was by explicit design or a side effect of the preprocessor technology used to implement the C with Classess predecessor to Standard C++.

    How is this related to your example? Basically because the Standard made overload resolution conform to the general rule that name lookup comes before access control.

    10.2 Member name lookup [class.member.lookup]

    1 Member name lookup determines the meaning of a name (id-expression) in a class scope (3.3.7). Name lookup can result in an ambiguity, in which case the program is ill-formed. For an id-expression, name lookup begins in the class scope of this; for a qualified-id, name lookup begins in the scope of the nestedname- specifier. Name lookup takes place before access control (3.4, Clause 11).

    8 If the name of an overloaded function is unambiguously found, overloading resolution (13.3) also takes place before access control. Ambiguities can often be resolved by qualifying a name with its class name.

提交回复
热议问题