There is a constant method, but it changes one of the fields. For the fact that this field can be changed in a constant object, I am responsible, but the compiler does not believe in the word, what can I do?

class A { public: void funct() const; private: int a; int b; } void A::funct() const { b++; } 

    1 answer 1

    Try adding mutable to the variable declaration: mutable int b; Read more here.

    • five
      - And even better - do not try: > One added mutable elementary can lead to mutable cascading piles and to the loss of the benefits of using const in general. - If you know exactly what you are doing, it is better to use const_cast<T> in a strictly defined place and document this crutch - why it is impossible / incredibly difficult to write const- correct code in a particular place. - Costantino Rupert
    • 2
      - As far as I know, in C++ mutable has only one application - the getter'а implementation with lazy initialization. In this case, it is worthwhile to localize the use of mutable in the helper class like suspension<T> from this example, and again, to document why the mutable. was written mutable. - Costantino Rupert
    • Hmm .. An interesting note .. - brightside90
    • one
      @ Kotik_hokhet_kusat: well, every internal cache should be mutable, in theory. - VladD
    • @ Kotik_khohet_kushat I would like to see how reference counting will look like, for example, without mutable =) You offer a crutch, if not a hack, instead of a design specially introduced for such purposes. Lazy initialization by reference has a bunch of flaws. For such a purpose, there is boost :: optional or a future std :: optional. - Dith