c++overload-resolutionprivate-methodspublic-methodfunction-qualifier

On a non-const object, why won't C++ call the const version of a member function with public-const and private-non-const overloads?


class C
{
public:
    void foo() const {}
private:
    void foo() {}
};

int main()
{
    C c;
    c.foo();
}

MSVC 2013 doesn't like this:

> error C2248: 'C::foo' : cannot access private member declared in class 'C'

If I cast to a const reference, it works:

const_cast<C const &>(c).foo();

Why can't I call the const member function on the nonconst object?


Solution

  • From the standard:

    13.3.3 If a best viable function exists and is unique, overload resolution succeeds and produces it as the result. Otherwise overload resolution fails and the invocation is ill-formed. When overload resolution succeeds, and the best viable function is not accessible (Clause 11) in the context in which it is used, the program is ill-formed.