Possible Duplicate:
C++ 'mutable' keyword
class student {
mutable int rno;
public:
student(int r) {
rno = r;
}
void getdata() const {
rno = 90;
}
};
Possible Duplicate:
C++ 'mutable' keyword
class student {
mutable int rno;
public:
student(int r) {
rno = r;
}
void getdata() const {
rno = 90;
}
};
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
}
};
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::map
s, which cannot be accessed using the index ing operator []
if they are const.
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...