Gaurav
Gaurav

Reputation: 1

Mutable Variable in Class -- Issue

#include <iostream>
using std::cout;

class Test
{
  public:
    int x;
    mutable int y;
    Test() 
    { 
      x = 4; y = 10; 
    }
   static void disp(int);
};

void Test::disp(int a)
{
    y=a;
    cout<<y;
}

int main()
{
    const Test t1;
    Test::disp(30);
    t1.y = 20;
    cout << t1.y;
    return 0;
}

I am getting error with in the constructor:

void Test::disp(int a)
{
    y=a;
    cout<<y;
}

I don't understand why this is not working because y is mutable and its already updated successfully within constructor Test() but when its coming to disp(). its shows error..

I have also checked with some other examples also . So I came to know you can update a mutable variable once only. If you try to update it more then one time it shows an error. Can anyone explain why this happening or reason behind it?

Upvotes: 0

Views: 174

Answers (1)

Martin G
Martin G

Reputation: 18109

Your problem doesn't have anything to do with mutable. You are trying to modify a non-static class member from a static method, which is not allowed. In your example it makes little sense to have the Test::disp method static in the first place.

You also seem to have misunderstood the meaning of mutable. It doesn't make members of a const object non-read-only. It makes it possible for const methods to write to members. Your code updated to show what mutable does:

#include <iostream>
using std::cout;

class Test
{
  public:
    int x;
    mutable int y;
    Test() 
    { 
      x = 4; y = 10; 
    }
   void disp(int) const; // Notice the const
};

void Test::disp(int a) const
{
    y=a; // ::disp can write to y because y is mutable
    cout<<y;
}

int main()
{
    Test t1;
    t1.disp(30);
    t1.y = 20;
    cout << t1.y;
    return 0;
}

And yes, there is no limit to the number of times a mutable variable can be written, just to be clear.

Upvotes: 1

Related Questions