×

C++ Mutable keyword

C++ mutable keyword

Mutable class storage specifier in C++ Storage class specifiers in C are auto, register, static, and external. Typedef is also considered as a specifier of the storage class in C. C++ also supports all of those specifiers for storage class. In addition to this C++, adds an absolutely essential specifier for storage class whose name is mutable.

What is the use of mutability?

There is often a need to change one or more class/struct data members by the const method, even though you don't want the method to update other class/struct members. Using a mutable keyword, we can easily accomplish this task.

Consider this example where it may be useful to use the mutable. Suppose you go to the hotel and give an order to the waiter to bring some dishes of food. You suddenly decide to change the order of the food after you give an order. Suppose that the hotel provides the services for changing the ordered food and start ordering new food within ten min after the first order is issued. The order can't be canceled after 10 minutes, and the old order cannot be replaced with the new order. For details, see the code below.

#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* q, char* r, int b, int p)
    {
        strcpy(name, q);
        strcpy(placedorder, r);
        tableno = b;
        bill = p;
    }
    void changePlacedOrder(char* p) const
    {
        strcpy(placedorder, p);
    }
    void changeBill(int q) const
    {
        bill = q;
    }
    void display() const
    {
        cout << "Customer name is: " << name << endl;
        cout << "Product placed by customer is: " << placedorder << endl;
        cout << "table no is: " << tableno << endl;
        cout << "Total amount: " << bill << endl;
    }
};
int main()
{
    const Customer cus1("Peter Johenson", "Cold drink", 4, 250);
    cus1.display();
    cus1.changePlacedOrder("chicken fry");
    cus1.changeBill(420);
    cus1.display();
    return 0;
}

Output:

C++ mutable keyword

Watch the output of the above program closely placed order qualities and bill information. The main is modified from const feature since they are decided to declare to be mutable.

The mutable keyword is primarily used to change a given const object member. The feature passed to this pointer has become const when we declare a feature to be const. Adding mutable to a variable allows for a change of members by a const pointer. Mutable is especially useful if most members are constant, but a few need to be updated. Members of the data clarified as mutable may be updated even if they are the part of the object defined const. The mutable specifier cannot be used with names declared static or const or reference.

As an exercise, it predicts the output of two programs that follow.

// PROGRAM 1
#include <iostream>
using std::cout;
class Test {
public:
  int t;
  mutable int p;
  Test() { t = 8; p = 15; }
};
int main()
{                                                                        
    const Test l1;
    l1.p = 50;
    cout << l1.p;
    return 0;
}

Output:

C++ mutable keyword

//PROGRAM2

#include <iostream>
using namespace std;
class Test {
   public:
      int w;
   mutable int k;
   Test(int e=0, int f=0) {
      w=e;
      k=f;
   }
   void setw(int e=0) {
      w = e;
   }
   void setk(int f=0) {
      k = f;
   }
   void disp() {
      cout<<endl<<"w: "<<w<<" k: "<<k<<endl;
   }
};
int main() {
   const Test t(25,30);
   cout<<t.w<<" "<<t.k<<"\n";
   t.k=200; //k still can be changed, because k is mutable.
   cout<<t.w<<" "<<t.k<<"\n";
   return 0;
}

Output:      

C++ mutable keyword

Related Topics

C++ Program to find the element that occurs once

Write a program to find the element in the array that occurs once. Given that all the numbers in the array are present two times and the array is sorted,...

7 minutes read.

C++ Functions

In other programming languages, a function is referred to as a process or a subroutine. We can design functions to execute any task. A function can be used repeatedly. It...

5 minutes read.

Structure of C++ Program

Many people believe that C++, an object-oriented programming (OOP) language, is the finest language for developing demanding applications. A superset of the C language is C++. Java, a closely comparable...

4 minutes read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

Difference between Two Sets in C++

The distinction between the two sets is made up of the components that are present in the first set but absent from the second set. The function consistently duplicates the...

3 minutes read.

Reverse a String using Stack C/C++

Reverse the given string using stack. To turn "tutorialandexample" into "elpmaxednalairotut," for instance. Here is a straightforward stack-based technique for reversing strings. Algorithm: 1) Make a stack that is empty. 2) Push each character...

3 minutes read.

C++ Enumeration

C++ Enumeration In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets...

3 minutes read.

Structured Binding in C++

Structured binding is the new feature of C++ 17. It is used to bind the specified name with an element of the initializer. Structure binding is used to declare multiple...

3 minutes read.

std::distance() in C++

The primary function of std::distance is to facilitate the total number of elements if we have two iterators. It is defined inside the header files. It has both magnitude and...

2 minutes read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

Vector resize() in C++

Vector resize() in C++ Vectors are called dynamic arrays and can automatically adjust their size when a component is added or deleted. This container is used for storage. The function modifies the...

3 minutes read.

C++ Data Abstraction

Object-oriented programming (OOP) provides a number of characteristics that enable programmers to design programmes based on a variety of ideas, reducing errors and increasing program flexibility. The abstraction of data...

7 minutes read.

What are local class and global class in C++

In C++, a class is a fundamental block that achieves object-oriented programming. The class holds its data members and member functions. Objects help to access the data elements and functions....

4 minutes read.

How to Handle Divide by Zero Exception in C++

If you are a programmer or interested in coding then it is obvious that you face some illogical test cases. Suppose, you have written one program that calculates the factorial...

6 minutes read.

Iostream in C++

Using Iostream in C++, we can perform input and output operation capabilities. This represents input and output, and the stream is used to carry out this capability. A stream is...

4 minutes read.

Containership in C++

In C++, it is possible to create an object in one class into another class, and that object is a member of another class. This relationship is known as a...

4 minutes read.

Binary Operator Overloading in C++

The Binary Operator Overloading in the C++ programming language will be covered in this part. An operator which comprises two operands to execute a mathematical operation is termed the Binary...

6 minutes read.

Palindrome Number Program in C++

A palindrome number is one that is the same when it is reversed. Palindrome numbers include 22, 33, 44, 55, 66, 77, 88, and 99. Algorithm for Palindrome Numbers Get the user's...

4 minutes read.

Do-While Loop Examples in C++

Before we move on the examples of Do-While loop, let’s learn little bit about the Do-While loop in C++ language. Do While loop An iterative loop that checks the condition at the...

5 minutes read.