overloading a const member function

Hi, all:
I defined a class A as follows.

1
2
3
4
struct A {
	void f() {cout << "A::void f()" << endl;}
	void f() const  {cout << "A::void f() const" << endl;}
} 


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.
Try adding this to main() and see what you get:

1
2
    const A b;
    b.f();
Right.

The non-const version is preferred. The only way to call the const version is to give it a const object (or cast to a const object).
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?
Topic archived. No new replies allowed.