Mutable Keyword
👋 Greetings to all! I hope you're doing well. In this post, I'd like to explain how the "mutable"
keyword works in C++.
I hope this post will be helpful to those who are new to programming or those who are looking for a
refresher on this
topic.
As we know, in C++, one of the uses for the "const" keyword is to indicate that an object is constant
and cannot be
modified. However, sometimes we may need to modify a member variable even if it is declared as const.
This is where the
"mutable" keyword comes in handy.
🤔 Let's consider a scenario where we have a Car class with a private attribute called "color" and a
public method named
"void changeColor() const". We also have an object of this class called "car" in our main function. Now,
if we wanted to
modify the color attribute, we can simply write "car.changeColor()". However, we may encounter an issue
here. What does
the "const" keyword mean when it is included in the method signature? In such cases, "const" means that
the parameter
implicit “car” will become a constant object within the "changeColor()" method (even though this object
wouldn't have
been declared as const in the main function) making it impossible to modify the color private attribute.
💡 To overcome this problem, we have two options to choose from, depending on our requirements.
➡️ The first option is to remove the "const" keyword from our "changeColor()" method if we need to
modify the color
attribute and possibly some other attributes in our Car class. This way, all attributes of our car
object can be
modified from this method.
➡️ Alternatively, we can use the "mutable" keyword if we wanted to protect the other attributes (not the
color one) from
being modified within this method.
To put it plainly, "a mutable attribute can be modified in any event, even when it belongs to a const
object".
I hope this post helps you better understand the "mutable" keyword in C++ and how it can be useful in
programming. If
you have any questions or comments, feel free to share them with us ✍️
Thank you for reading, and I wish you a great day ahead! 😁