यहां हम देखेंगे कि C++ में म्यूटेबल कीवर्ड क्या है। परिवर्तनीय सी ++ में स्टोरेज क्लास में से एक है। म्यूटेबल डेटा सदस्य उस तरह के सदस्य होते हैं, जिन्हें हमेशा बदला जा सकता है। भले ही ऑब्जेक्ट कॉन्स्ट टाइप हो। जब हमें केवल एक सदस्य को चर के रूप में और दूसरे को स्थिर के रूप में चाहिए, तो हम उन्हें परिवर्तनशील बना सकते हैं। आइए विचार प्राप्त करने के लिए एक उदाहरण देखें।
उदाहरण
#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();
} आउटपुट
[Error] passing 'const MyClass' as 'this' argument of 'void MyClass::setx(int)' discards qualifiers [-fpermissive]निकल जाते हैं।
यदि हम लाइन को हटाकर प्रोग्राम चलाते हैं [ s.setx(150); ], फिर -
आउटपुट
Before Change: (x: 15 y: 25) After Change: (x: 15 y: 250)