0

Possible Duplicate:
C++ 'mutable' keyword

class student {

   mutable int rno;

   public:
     student(int r) {
         rno = r;
     }
     void getdata() const {
         rno = 90;
     } 
}; 
Community
  • 1
  • 1
Ivin Polo Sony
  • 355
  • 3
  • 17

3 Answers3

2

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
     }
};
bitmask
  • 32,434
  • 14
  • 99
  • 159
  • does the presence of any const member function make the member variables read only? – Ivin Polo Sony Aug 25 '12 at 14:08
  • @IvinPoloSony: Yes and no. Just inside the member function(s) that have the `const` qualifier. Let me edit my answer ... – bitmask Aug 25 '12 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. – Ivin Polo Sony Aug 25 '12 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 Aug 25 '12 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.

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
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...

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 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. – Richard J. Ross III Aug 25 '12 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`... – Luchian Grigore Aug 25 '12 at 14:06