So A has two member functions f() and the only difference is that one of them is labeled const. Intuitively I think this should be an compile error, because anyway, how could the compiler possibly knew which version you call when there's no difference in parameters?
The strange thing is that such code is well compiled and when calling f(), it always invokes the non-const member. Every one can try with the following main function.
1 2 3 4 5 6
int main()
{
A a;
a.f();
return 0;
}
Anyone knows what's the reason of this? Many thanks.
Hi, PanGalactic and Disch:
What you said is especially helpful. I think it solved the problem. Here's another problem when I was trying to implement PanGalactic's code: if I directly define const A b;
then the compiler complains that b is uninitialized. So I add into A explicitly a default constructor and then everything is fine, i.e.,
1 2 3 4
class A {
A() {}
// other stuff as before
};
If without explicitly adding the default constructor, I can use const A & b=a;
the compiler is also OK with it. This part I understand. But why the compiler can not use the synthesized constructor to initialize a const object directly? Any suggestions?