Member function with const modifier.

765 Views Asked by At

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?

2

There are 2 best solutions below

4
On BEST ANSWER

Why is non-const dosmth being called?

That is by design. If you have a non-const object, the non-const overload is chosen over the const one.

ow can I call const version explicitly?

You need a context where your object is const. For example,

void dofoo(const Foo& f) { f.dosmth(); }
int main()
{
  CFoo foo;
  dofoo(foo);
  cout << CFoo::a << endl;

or

int main()
{
  const CFoo foo1{};
  foo1.dosmth();
  CFoo foo2;
  const_cast<const CFoo&>(foo2).dosmth();
}
0
On

The const version is only called when the object itself is const. This means you can call the const version with this code:

int main(){
    const CFoo foo;
    cout << CFoo::a << endl;
    foo.dosmth();
    cout << CFoo::a << endl;
}