What is need for Mutable?
- Data members cannot be changed in const objects.
- In some scenarios this is required and mutable keyword provides the solution.
Demonstrate the usage of mutable keyword
#include <iostream>
using namespace std;
class MyClass {
mutable int x;
int y;
public:
MyClass (int a, int b)
{
x=a;
y=b;
}
void SetX(int a) const
{
x=a;
}
void SetY(int b) const
{
/* Compilation Error
y=b;
Error E2024 mutable.cpp 21: Cannot modify a const object in function MyClass::SetY(int) const
*/
}
};
int main() {
// Create a const object
const MyClass obj(5,5);
obj.SetX(10);
return 0;
}
0 comments:
Post a Comment