Is it possible to change the value of the Member variable in the const function?

The value of a constant variable can be changed using pointer tricks, but is it possible to do something like this:

    class A (){
       int x;
    public:
       void func () const {
          //change value of x here
    }
}
+4
source share
5 answers

Although not appreciated, C ++ provides a "Backdoor" that can be used to violate your own rules, just like dirty pointer tricks. In any case, you can easily do this using the cast version of the "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 
        }
 }
+3
source

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 a constant from a pointer this.
+6

x mutable

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

, // const ness /// const ness.

:

  • const, mutable.
  • const.
+1

'this', , , , .

    class CAST_CLASS (){
       int var;
    public:
       void change_CAST () const {

     CAST_CLASS* pointer =  const_cast<CAST_CLASS*> (this);
     pointer->var= 10;     
    }};
+1

Source: https://habr.com/ru/post/1608250/


All Articles