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

前端 未结 11 1097
天涯浪人
天涯浪人 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 10:03

    Ultimately this comes down to the assertion in the standard that accessibility should not be taken into consideration when performing overload resolution. This assertion may be found in [over.match] clause 3:

    ... When overload resolution succeeds, and the best viable function is not accessible (Clause [class.access]) in the context in which it is used, the program is ill-formed.

    and also the Note in clause 1 of the same section:

    [ Note: The function selected by overload resolution is not guaranteed to be appropriate for the context. Other restrictions, such as the accessibility of the function, can make its use in the calling context ill-formed. — end note ]

    As for why, I can think of a couple of possible motivations:

    1. It prevents unexpected changes of behaviour as a result of changing the accessibility of an overload candidate (instead, a compile error will occur).
    2. It removes context-dependence from the overload resolution process (i.e. overload resolution would have the same result whether inside or outside the class).

提交回复
热议问题