Mutable Variables
Published Nov 15, 2024
Contribute to Docs
In C++, mutable variables are variables that can be modified even within constant functions, useful for managing internal state flexibly.
Syntax
To declare a variable as mutable, the mutable
keyword needs to be placed before the variable type:
mutable type name;
type
: The type of the variable (e.g.,int
,char
).name
: The name of the variable.
Example
In the example below, accessCount
is marked mutable
, allowing it to be modified within the constant displayData()
function:
#include <iostream>#include <string>class Data {public:Data(std::string value) : data(value), accessCount(0) {}void displayData() const {++accessCount; // Modification allowed due to 'mutable'std::cout << "Data: " << data << ", Access count: " << accessCount << std::endl;}private:std::string data;mutable int accessCount; // Can be modified in constant methods};int main() {Data d("Sample");d.displayData();d.displayData();return 0;}
The above code produces the following output:
Data: Sample, Access count: 1Data: Sample, Access count: 2
Here, even though displayData()
is a constant member function, accessCount
can be incremented due to its mutable
declaration.
Codebyte Example
The following codebyte example demonstrates the usage of mutable variables:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours