Click to See Complete Forum and Search --> : How can I Invoke a const member function in a class?


peng-jr
May 13th, 1999, 04:03 AM
When I learn the STL,I find that we can define such a class:
class A {
public:
int a;
A(int x=0):a(x) {};
int GetA() { return a++;};
int GetA() const { return a;};
};

But I find when I call the GetA method,the non-const method will be invoked
always,for example:

void main()
{
A t(10);
cout<<t.GetA()<<endl; //call non-const method
cout<<t.GetA()<<endl; //call non-const method
}

Can anybody tell me how I invoke the const method without deleting the
non-const one?

Paul McKenzie
May 13th, 1999, 04:47 AM
You need to call GetA with a const A object. Here are the ways that I have used to do what you want:

const A* pt = &t;
cout<< pt->GetA() << endl;

OR

cout << ((const A*)(&t))->GetA() << endl;

Regards,

Paul McKenzie