I have a class with two member functions which are differ only by const
modifier.
class CFoo
{
private:
int x;
int y;
public:
static int a;
void dosmth() const {
a = 99;
}
void dosmth(){
x++;
y++;
}
};
int CFoo::a = 100;
int main(){
CFoo foo;
cout << CFoo::a << endl;
foo.dosmth();
cout << CFoo::a << endl;
}
The following code prints 100, 100
. Why is non-const dosmth being called? How can I call const
version explicitly?
That is by design. If you have a non-const object, the non-const overload is chosen over the
const
one.You need a context where your object is
const
. For example,or