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.