C++ – Why Won’t Non-Const Object Call Const Version of Member Function?

c++function-qualifieroverload-resolutionprivate-methodspublic-method

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?

Best Answer

The object is not const, so the non-const overload is a better match. Overload resolution happens before access checking. This ensures that overload resolution is not inadvertently changed by changing the access of a member function.