-2
class StatDemo
{
   private: static int x;
   int y;
   public: void setx(int a) const { x = a; }
   void sety(int b) const { y = b; }
   int getx() {return x; }
   int gety() {return y; }
} ;

What is the use of const when the member variables are changed by the function??

  • 1
    "What is the use of const..." To cause compiler error? – songyuanyao Sep 19 '16 at 02:41
  • It looks like you've mistakenly made the setters const, and the getters non-const. It should be the other way around. And this stuff should all be _inside_ the class definition, not after it. – paddy Sep 19 '16 at 02:43

2 Answers2

1

methods not marked const cannot be called on a const object (or ref or pointer to a const object).

StatDemo sd;
StatDemo const & sdr = sd;
sdr.get(x); // error because getx isn't marked const

However, that means that all the data members accessed from within a method marked const are also const, so you cannot change them (without playing tricks).

That's why your setx won't compile -- x is const within those methods.

xaxxon
  • 19,189
  • 5
  • 50
  • 80
0

What is the use of const when the member variables are changed by the function?

As @songyuanyao correctly mentioned, to cause compile errors.

Yet, it is rather a convention. You may still modify members via const_cast on this, or via marking members mutable.

There's a difference between logical and physical constness, as discussed here.

Why may we still modify non-const static members in const methods?

A non-static method of a class has this as a parameter. const qualifier on a method makes this constant (and triggers a compile error when the convention's violated).

A static member isn't related to this in any way: it is the only one for every object of a class. That's why the constness of a method (i.e. the constness of this) has no impact on static members of a class.

Nestor
  • 687
  • 5
  • 12