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

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

Consider this code:

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

    private:

        void foo()
           


        
11条回答
  •  梦毁少年i
    2020-12-25 09:52

    This comes down to a fairly basic design decision in C++.

    When looking up the function to satisfy a call, the compiler carries out a search like this:

    1. It searches to find the first1 scope at which there's something with that name.

    2. The compiler finds all the functions (or functors, etc.) with that name in that scope.

    3. Then the compiler does overload resolution to find the best candidate among those it found (whether they're accessible or not).

    4. Finally, the compiler checks whether that chosen function is accessible.

    Because of that ordering, yes, it's possible that the compiler will choose an overload that's not accessible, even though there's another overload that's accessible (but not chosen during overload resolution).

    As to whether it would be possible to do things differently: yes, it's undoubtedly possible. It would definitely lead to quite a different language than C++ though. It turns out that a lot of seemingly rather minor decisions can have ramifications that affect a lot more than might be initially obvious.


    1. "First" can be a little complex in itself, especially when/if templates get involved, since they can lead to two-phase lookup, meaning there are two entirely separate "roots" to start from when doing the search. The basic idea is pretty simple though: start from the smallest enclosing scope, and work your way outward to larger and larger enclosing scopes.

提交回复
热议问题