Search code examples
c++overloadingprotected

Why can't I access a public function that has a protected overload?


Given the code:

class Foo
{
public:
    Foo() {}

    int foo() const { return 6; }
protected:
    int foo() { return 5; }
};

int main(int argc, char* argv[])
{
    Foo foo;
    foo.foo();
    return 0;
}

I get a compile error:

'Foo::foo' : cannot access protected member declared in class 'Foo'

In actual usage, I'm trying to provide a function that returns a pointer to an object that the class is storing - modifiable for the members, and const for everyone else. I figured that if I say

const Item *i = foo.foo();

in a non-member function, the correct, const variant will be called. Somehow though, the compiler insists on accessing the non-const variant in the protected section. Any idea why? Thanks.


Solution

  • Your variable is non-const, so the non-const overload of the function is selected. After overload resolution occurs, then accessibility is checked.

    When const and non-const functions both exist, the const version is only called on const objects. Your foo variable is not const. You can make it const with a const_cast if you want:

    const_cast<Foo const&>(foo).foo();
    

    That's cumbersome to use, though. A better solution would be to just give the internal function a different name so it doesn't clash with the external API.