Mutable keyword in C++?

C++Server Side ProgrammingProgramming

Here we will see what is the mutable keyword in C++. The mutable is one of the storage class in C++. Mutable data members are that kind of member, which can be changed always. Even if the object is const type. When we need only one member as variable and other as constant, then we can make them mutable. Let us see one example to get the idea.

Example

#include <iostream>
using namespace std;
class MyClass{
   int x;
   mutable int y;
   public:
   MyClass(int x=0, int y=0){
      this->x = x;
      this->y = y;
   }
   void setx(int x=0){
      this->x = x;
   }
   void sety(int y=0) const { //member function is constant, but data will be changed
      this->y = y;
   }
   void display() const{
      cout<<endl<<"(x: "<<x<<" y: "<<y << ")"<<endl;
   }
};
int main(){
   const MyClass s(15,25); // A const object
   cout<<endl <<"Before Change: ";
   s.display();
   s.setx(150);
   s.sety(250);
   cout<<endl<<"After Change: ";
   s.display();
}

Output

[Error] passing 'const MyClass' as 'this' argument of 'void MyClass::setx(int)' discards qualifiers [-fpermissive]

If we run the program by removing the line [ s.setx(150); ], then −

Output

Before Change:
(x: 15 y: 25)
After Change:
(x: 15 y: 250)
raja
Updated on 20-Aug-2019 11:03:31

Advertisements