0

I have some class for a collector, and there are 2 methods, for example:

bool MyCollectorChanged() const;
bool MyCollectorDoSomeOperation() const;

I can't change the signatures of these methods which means I can't remove the const from the signature.

I want to set/unset some flag in MyCollectorChanged() for some situation, so I could check the flag value inside MyCollectorDoSomeOperation().

Adding a member flag to the class will not work, as MyCollectorChanged() is a const method so I can't change the member flag inside MyCollectorChanged().

Is there an option to do it? How can I set/unset some flag inside MyCollectorChanged(), so it will be visible inside MyCollectorDoSomeOperation()?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
gadiiii
  • 3
  • 1

1 Answers1

4

Option 1

If you have the option of changing the attributes of the private member variables, you can make some of them mutable. Then, you will be able to change their values in a const member function.

See http://en.cppreference.com/w/cpp/language/cv for more info.

Option 2

If you have option of using the Pimpl idiom, you will be able to change the value of any member variable in the class/struct that represents the data of the main class.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • How about overloading the method by removing `const`? Will it work? – CinCout May 11 '16 at 05:25
  • @CinCout, I think the OP wants to update the data in the `const` member functions. – R Sahu May 11 '16 at 05:30
  • Agreed. But is overloading a possible solution to achieve the same? To set/reset flag in the non-const method, and call the `const` one from the non-const one to avoid code duplicacy? – CinCout May 11 '16 at 05:34
  • @CinCout, that would work if the function is called on a non-`const` object but won't work if the function is called on a `const` object. – R Sahu May 11 '16 at 05:36