1

Possible Duplicate:
C++ 'mutable' keyword

class student {

   mutable int rno;

   public:
     student(int r) {
         rno = r;
     }
     void getdata() const {
         rno = 90;
     } 
}; 
0

3 Answers 3

3

It allows you to write (i.e. "mutate") to the rno member through a student member function even if used with a const object of type student.

class A {
   mutable int x;
   int y;

   public:
     void f1() {
       // "this" has type `A*`
       x = 1; // okay
       y = 1; // okay
     }
     void f2() const {
       // "this" has type `A const*`
       x = 1; // okay
       y = 1; // illegal, because f2 is const
     }
};
4
  • does the presence of any const member function make the member variables read only? Commented Aug 25, 2012 at 14:08
  • @IvinPoloSony: Yes and no. Just inside the member function(s) that have the const qualifier. Let me edit my answer ...
    – bitmask
    Commented Aug 25, 2012 at 14:09
  • So for a const function to update a member variable it has to be mutable Right?. normal member functions can anyways edit member variables. Commented Aug 25, 2012 at 14:20
  • @IvinPoloSony: Exactly. However, note that this is extremely dirty. Using mutable is often an indicator that you're doing something wrong. It's not always the case (there are legitimate use cases for it) but often.
    – bitmask
    Commented Aug 25, 2012 at 14:25
1

The mutable keyword is used so that a const object can change fields of itself. In your example alone, if you were to remove the mutable qualifier, then you would get a compiler error on the line

rno = 90;

Because an object that is declared const cannot (by default) modify it's instance variables.

The only other workaround besides mutable, is to do a const_cast of this, which is very hacky indeed.

It also comes in handy when dealing with std::maps, which cannot be accessed using the index ing operator [] if they are const.

1

In your particular case, it's used to lie and deceive.

student s(10);

You want data? Sure, just call getdata().

s.getdata();

You thought you'd get data, but I actually changed s.rno to 90. HA! And you thought it was safe, getdata being const and all...

2
  • 1
    I'm not sure that this style of post (rhetorical humor) is best for SO. I could understand on meta, but this seems almost insulting to the OP. For that reason, I have downvoted your post. Commented Aug 25, 2012 at 14:05
  • 1
    @RichardJ.RossIII well, I certainly see your point, but the question is Why is Mutable keyword used, and not what does mutable mean... Commented Aug 25, 2012 at 14:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.