- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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; }
Advertisements
To Continue Learning Please Login
Login with Google