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.


#include <iostream>
using namespace std;
class MyClass{
   int x;
   mutable int y;
   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: ";
   cout<<endl<<"After Change: ";


[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 −


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