Search code examples
c++overloadingfunction-qualifier

Member function with const modifier.


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?


Solution

  • 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();
    }