
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ mutable keyword?
Mutable data members are those members whose values can be changed in runtime even if the object is of constant type. It is just opposite to constant.
Sometimes logic required to use only one or two data member as a variable and another one as a constant to handle the data. In that situation, mutability is very helpful concept to manage classes.
Example
#include <iostream> using namespace std; code class Test { public: int a; mutable int b; Test(int x=0, int y=0) { a=x; b=y; } void seta(int x=0) { a = x; } void setb(int y=0) { b = y; } void disp() { cout<<endl<<"a: "<<a<<" b: "<<b<<endl; } }; int main() { const Test t(10,20); cout<<t.a<<" "<<t.b<<"\n"; // t.a=30; //Error occurs because a can not be changed, because object is constant. t.b=100; //b still can be changed, because b is mutable. cout<<t.a<<" "<<t.b<<"\n"; return 0; }
- Related Articles
- Mutable keyword in C++?
- Difference between mutable and immutable object
- The mutable storage class in C++
- Why StringBuffer is mutable in Java?
- Difference between mutable and immutable in python?
- Range Sum Query 2D - Mutable in C++
- Name mutable and immutable objects in Python
- Do you think Python Dictionary is really Mutable?
- How to create a mutable list with repeating elements in Kotlin?
- What is the difference between a mutable and immutable string in C#?
- PHP final Keyword
- Java static keyword
- Java strictfp keyword
- C# orderby Keyword
- C# into keyword

Advertisements