C++ – private non-const and public const member function – coexisting in peace

ccompiler-errors

I am trying to create a class with two methods with the same name, used to access a private member. One method is public and const qualified, the other is private and non-const (used by a friend class to modify the member by way of return-by-reference).

Unfortunately, I am receiving compiling errors (using g++ 4.3): When using a non-const object to call the method, g++ complains that the non-const version of my method is private, even though a public (const) version exists.

This seems strange, because if the private non-const version does not exist, everything compiles fine.

Is there any way to make this work?
Does it compile on other compilers?

Thanks.

Example:

class A
{
public:
    A( int a = 0 ) : a_(a) {}
public:
    int   a() const { return a_; }
private:
    int & a()       { return a_; } /* Comment this out, everything works fine */
    friend class B;
private:
    int a_;
};


int main()
{
    A       a1;
    A const a2;

    cout << a1.a() << endl; /* not fine: tries to use the non-const (private) version of a() and fails  */
    cout << a2.a() << endl; /* fine: uses the const version of a() */
}

Best Answer

Overload resolution happens before access checking, so when you call the a method on a non-const A, the non-const member is chosen as a better match. The compiler then fails due to the access check.

There is no way to "make this work", my recommendation would be to rename the private function. Is there any need to have a private accessor?