When we create a const object none of its data members can change.In a rare situation,however,you may want some data member should be allowed to change despite the object being const.
This can be achieved by the mutable keyword.This is shown in the following example:
#include<iostream.h>
class sample
{
private:
mutable int i;
public:
sample(int x=0)
{
i=x;
}
void fun() const
{
i++;
cout<<i;
}
};
void main()
{
const sample s(15);
s.fun();
}
Here,the object s is const and hence only const functions can operate on it.When the const function fun() gets called to operate on object s,the data member i is incremented.Ideally the data member should not be changed,as object is defined as const.But we can change the data member i because it is declared as mutable in the call sample.
This can be achieved by the mutable keyword.This is shown in the following example:
#include<iostream.h>
class sample
{
private:
mutable int i;
public:
sample(int x=0)
{
i=x;
}
void fun() const
{
i++;
cout<<i;
}
};
void main()
{
const sample s(15);
s.fun();
}
Here,the object s is const and hence only const functions can operate on it.When the const function fun() gets called to operate on object s,the data member i is incremented.Ideally the data member should not be changed,as object is defined as const.But we can change the data member i because it is declared as mutable in the call sample.
No comments:
Post a Comment