C++ Mutable Keyword: The Mutable Storage Class Speci Er in C++ (Or Use of Mutable Keyword in C++)
C++ Mutable Keyword: The Mutable Storage Class Speci Er in C++ (Or Use of Mutable Keyword in C++)
The mutable storage class speci er in C++ (or use of mutable keyword in C++)
auto, register, static and extern are the storage class speci ers in C. typedef is also considered as a storage class speci er in C. C++ also
supports all these storage class speci ers. In addition to this C++, adds one important storage class speci er whose name is mutable.
#include <iostream>
#include <string.h>
using std::cout;
using std::endl;
class Customer
{
char name[25];
mutable char placedorder[50];
int tableno;
mutable int bill;
public:
Customer(char* s, char* m, int a, int p)
{
strcpy(name, s);
strcpy(placedorder, m);
tableno = a;
bill = p;
}
void changePlacedOrder(char* p) const
{
strcpy(placedorder, p);
}
void changeBill(int s) const
{
bill = s;
}
void display() const
{
cout << "Customer name is: " << name << endl;
cout << "Food ordered by customer is: " << placedorder << endl;
cout << "table no is: " << tableno << endl;
cout << "Total payable amount: " << bill << endl;
}
};
int main()
{
const Customer c1("Pravasi Meet", "Ice Cream", 3, 100);
c1.display();
c1.changePlacedOrder("GulabJammuns");
c1.changeBill(150);
c1.display();
return 0;
}
Output:
Closely observe the output of above program. The values of placedorder and bill data members are changed from const function because they
are declared as mutable.
The keyword mutable is mainly used to allow a particular data member of const object to be modi ed. When we declare a function as const,
the this pointer passed to function becomes const. Adding mutable to a variable allows a const pointer to change members.
mutable is particularly useful if most of the members should be constant but a few need to be updateable. Data members declared as mutable
can be modi ed even though they are the part of object declared as const. You cannot use the mutable speci er with names declared as static
or const, or reference.
// PROGRAM 1
#include <iostream>
using std::cout;
class Test {
public:
int x;
mutable int y;
Test() { x = 4; y = 10; }
};
int main()
{
const Test t1;
t1.y = 20;
cout << t1.y;
return 0;
}
// PROGRAM 2
#include <iostream>
using std::cout;
class Test {
public:
int x;
mutable int y;
Test() { x = 4; y = 10; }
};
int main()
{
const Test t1;
t1.x = 8;
cout << t1.x;
return 0;
}
Source:
The mutable storage class speci er (C++ only)