Is it possible change value of Member variable within "const" function?

Though this is not appreciated, but C++ provides “Backdoors” which can be used to breach its own regulations, just like dirty pointer tricks. Anyway, you can easily do this by using a casted version of “This” pointer :

class A (){
           int x;
        public:
           void func () const {
              //change value of x here
         A* ptr =  const_cast<A*> (this);
         ptr->x= 10;     //Voila ! Here you go buddy 
        }
 }

declare x mutable

class A (){
   mutable int x;
public:
   void func () const {
      //change value of x here
   }
}; 

You have two options:

class C
{
public:
    void const_f() const
    {
        x = 5;                               // A
        auto* p_this = const_cast<C*>(this); // B
        p_this->y = 5;
    }

private:
    mutable int x;                           // A
    int y;
};
  • A: declare certain members mutable.
  • B: const_cast to remove constness from the this pointer.

Tags:

C++

Visual C++