
- 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
Mutable keyword in C++?
Here we will see what is the mutable keyword in C++. The mutable is one of the storage class in C++. Mutable data members are that kind of member, which can be changed always. Even if the object is const type. When we need only one member as variable and other as constant, then we can make them mutable. Let us see one example to get the idea.
Example
#include <iostream> using namespace std; class MyClass{ int x; mutable int y; public: MyClass(int x=0, int y=0){ this->x = x; this->y = y; } void setx(int x=0){ this->x = x; } void sety(int y=0) const { //member function is constant, but data will be changed this->y = y; } void display() const{ cout<<endl<<"(x: "<<x<<" y: "<<y << ")"<<endl; } }; int main(){ const MyClass s(15,25); // A const object cout<<endl <<"Before Change: "; s.display(); s.setx(150); s.sety(250); cout<<endl<<"After Change: "; s.display(); }
Output
[Error] passing 'const MyClass' as 'this' argument of 'void MyClass::setx(int)' discards qualifiers [-fpermissive]
If we run the program by removing the line [ s.setx(150); ], then −
Output
Before Change: (x: 15 y: 25) After Change: (x: 15 y: 250)
- Related Articles
- C++ mutable keyword?
- 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
- Difference between mutable and immutable object
- 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#?
- Static Keyword in C++
- “extern” keyword in C
- “register” keyword in C
- Restrict keyword in C
- override Keyword in C++

Advertisements