Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting around const'ness of a C++ method in derived class

I have to use a framework which defines an important hook method as const, like this

class FrameworkClass {
  ...
  virtual void OnEventA(unsigned value) const;
  ...
}

In my derived class I have to save the value that I get through the hook

class MyClass: public FrameworkClass
{
  ...
  virtual void OnEventA(unsigned value) const { savedValue = value; } // error!

private:
  unsigned savedValue;
}

Unfortunately I can't change the framework.

Is there a good way to get around the const'ness of the hook method ?

like image 798
Gene Vincent Avatar asked Sep 02 '25 01:09

Gene Vincent


2 Answers

Make the variable mutable:
mutable unsigned savedValue;

like image 57
Kiril Kirov Avatar answered Sep 04 '25 15:09

Kiril Kirov


mutable is too "broad" workaround because affects methods that use const'ness correctly. to workaround inappropriate const'ness there's const_cast:

class MyClass: public FrameworkClass
{
  ...
  virtual void OnEventA(unsigned value) const { const_cast<MyClass*>(this)->savedValue = value; } // error!

private:
  unsigned savedValue;
}
like image 32
Andriy Tylychko Avatar answered Sep 04 '25 16:09

Andriy Tylychko