3

The following code does not compile:

struct A {
    void f () const { }
private:
    void f () { }
};

int main () {
    A a_nc;
    const A a_c;
    a_nc.f();
    a_c.f();
    return 0;
}

The error:

test.cpp: In function 'int main()':
test.cpp:4:10: error: 'void A::f()' is private
     void f () { }
          ^
test.cpp:10:12: error: within this context
     a_nc.f();
            ^

I am using g++ (tdm64-1) 5.1.0 on Windows.

I don't understand why the compiler is not able to fall back to the const qualified method f when the non const qualified method is not available?

I can't think of context where allowing the compiler to use the const-qualified method instead of the non const-qualified method would make the program behave oddly, is there any? And if not, why is it not allowed to do so?

Edit:

I have already seen this question: In c++, why does the compiler choose the non-const function when the const would work also?

But in the above, both methods are available, so the choice is clear to me. In my case, one method is not available but the compiler is not available to choose the other one, instead it fails to compile.

imz -- Ivan Zakharyaschev
  • 4,921
  • 6
  • 53
  • 104
Holt
  • 36,600
  • 7
  • 92
  • 139
  • I don't have an answer, but you can force it by using class method pointers. – xaxxon Jan 12 '16 at 08:40
  • re edit: that's why I hammered on a different question. – T.C. Jan 12 '16 at 08:46
  • @T.C. Your duplicate clearly answers my question, thanks. Is there a way to not show the other one at the top of this question? – Holt Jan 12 '16 at 08:47
  • @holt read the "c++ annotation" bit in the link this is closed as a duplicate of. It states the exact requirement in c++ that demands this behavior. – xaxxon Jan 12 '16 at 08:48
  • @xaxxon The "c++ annotation" bit states that the compiler chose the closest match, but what I was looking for was why the access was not taken into account into the "closest match" definition. The quote from the reference in T.C. post clearly answer this part. – Holt Jan 12 '16 at 08:53
  • Just leaving the link here, for the next hammerer passing by: http://stackoverflow.com/questions/25316779/on-a-nonconst-object-why-wont-c-call-the-const-version-of-a-method-with-publ?lq=1 – T.C. Jan 12 '16 at 09:16

1 Answers1

0

Because it first chooses a method by overload resolution. Once the one method to be called is determined, it is checked whether you have the right access rights. In other words, access specifiers do not affect overload resolution.

Florian Kaufmann
  • 803
  • 6
  • 13