c++ – Const Methods

Question:

Please enlighten about constant methods in C ++; why are we needed, what are the advantages ?! With small examples of code, if not difficult.

Answer:

Constant methods are used to determine what can be done to a class without side effects on its state, and what changes its state. In some cases, for example, the user of a class in which const correctly placed can avoid unnecessary copying of objects without losing data. Also, with the correct use of const at the compilation level, an accidental change of an object in a method is excluded, which should not change anything in the object. For example, there is a class like

class A
{
  int a;
  int b;
  public:
  int getA() { b = b + 1;return a; }
  int getB() { a = a + 1;return b; }
};

Here the mnemonics and semantics are slightly inconsistent. I want to think that if

A x, y;
...
bool f = x.getA() == y.getA() && x.getB() == y.getB();

f true, then x and y are somewhat similar, but the internals of the class are not implemented that way. The user of the class needs to be sure that the getter doesn't mess up anything. A good class designer should explicitly describe the behavior of a method using const or no const

class A
{
  int a;
  int b;
  public:
  int getA() const { return a; }
  int getB() const { return b; }
};

But if you suddenly need to make a program in which there is something like counting calls to a variable, then the semantics of getters forces you to use const , but the counter of calls needs to be increased. For this case, there is the word mutable ! With this word, we mark the fields that seem to be members of the class, but they do not reflect something like its state

class A
{
  int a;
  int b;
  mutable int cntA;
  mutable int cntB;
  public:
  int getA() const { cntA++; return a; }
  int getB() const { cntB++; return b; }
};
Scroll to Top