C%20%20%20Interview%20Questions%20and%20Answers
Question: What is "mutable"?
Answer: Answer1. "mutable" is a C++ keyword. When we declare const, none of its data members can change. When we want one of its members to change, we declare it as mutable. Answer2. A "mutable" keyword is useful when we want to force a "logical const" data member to have its value modified. A logical const can happen when we declare a data member as non-const, but we have a const member function attempting to modify that data member. For example: class Dummy { public: bool isValid() const; private: mutable int size_ = 0; mutable bool validStatus_ = FALSE; // logical const issue resolved }; bool Dummy::isValid() const // data members become bitwise const { if (size > 10) { validStatus_ = TRUE; // fine to assign size = 0; // fine to assign } } Answer2. "mutable" keyword in C++ is used to specify that the member may be updated or modified even if it is member of constant object. Example: class Animal { private: string name; string food; mutable int age; public: void set_age(int a); }; void main() { const Animal Tiger(â??Fulffyâ??,'antelopeâ??,1); Tiger.set_age(2); // the age can be changed since its mutable } |
Is it helpful?
Yes
No
Most helpful rated by users:
- What is C++?
- What is function overloading and operator overloading?
- How do you find out if a linked-list has an end? (i.e. the list is not a cycle)
- What is the difference between declaration and definition?
- What is the difference between realloc() and free()?