VOOZH about

URL: https://www.geeksforgeeks.org/cpp/c-mutable-keyword/

⇱ C++ mutable keyword - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C++ mutable keyword

Last Updated : 9 Jun, 2026

The mutable keyword in C++ allows specific data members to be excluded from the const restrictions imposed on an object. It is commonly used when certain information needs to be updated without changing the logical state of the object.

  • Enables controlled modification of selected data members
  • Useful for maintaining auxiliary information such as counters, caches, or status data
  • Helps preserve logical constness while permitting internal updates

Syntax

mutable data_type variable_name;


Output
Customer name is: Pravasi Meet
Food ordered by customer is: Ice Cream
table no is: 3
Total payable amount: 100
Customer name is: Pravasi Meet
Food ordered by customer is: GulabJammuns
table no is: 3
Total payable amount: 150

Explanation

  • The object c1 is declared as const, so regular data members cannot be modified.
  • The members placedorder and bill are declared as mutable, allowing them to be updated inside const member functions.
  • Therefore, the order and bill values change successfully even though the object is const.

Rules of mutable Keyword

  • Data members declared as mutable can be modified inside const member functions.
  • In a const member function, the object is treated as const, but mutable members can still be modified.
  • It is useful when only a few members need to be updated while the rest of the object remains constant.
  • The mutable specifier cannot be applied to static, const, or reference members.

mutable with Const Objects


Output
Display Called: 1 times
Display Called: 2 times

Explanation: Although s is a constant object, the mutable variable accessCount can still be modified.

Advantages of mutable Keyword

  • Allows modification of selected members in const functions.
  • Useful for caching and performance optimization.
  • Helps maintain logical constness.
  • Supports logging and monitoring operations.

Limitations of mutable Keyword

  • Excessive use can make code harder to understand.
  • May weaken the guarantees provided by const.
  • Should only be used for data that does not represent the logical state of an object.
Comment
Article Tags: