Change the value of member variable of a const function in C++

In this tutorial, we will learn to change the value of member variable of a const function in c++. For this, we will use the mutable keyword in C++.

The keyword mutable is mainly used to allow a particular  data member of const object to be modified

Check Here: mutable 

Approach:

  1. Firstly, create a class in which member variable is to be declared.
  2. Now, Declare member variable as mutable by using mutable keyword.
  3. In the setValue() function, we will change the value of member variable.
  4. Also, create printNumber() function to print the value of the variable.

The implementation  of the above approach is given below:

#include <iostream>
using namespace std;

// creating example class
class Example {
    private:
    mutable int number;
    public:
    // const function is changing the value of the number 
    void setValue(int value) const{
        number = value;
        number++;
    }
    // it will print the value of the number 
    void printNumber() {
        cout << "value of number is: " << number << endl;
    }
};


int main()
{
    Example obj; // creating the object
    obj.setValue(12); // setting value to 12
    obj.printNumber(); // printing the number
}

Output:

value of number is: 13

Also Check: sort all file names by their sizes

Leave a Reply

Your email address will not be published. Required fields are marked *