Wednesday, May 28, 2008

C++ Mutable

1 comment
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.
EXAMPLE: 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;
}

If You Enjoyed This, Take 5 Seconds To Share It

1 comment:

  1. WOW! This is the best C++ tutorial all over the Internet! Thanks a lot for your efforts! You help me so much!

    ReplyDelete