C++ Program to Implement a Class with Mutable Members

This C++ program illustrates the concept of mutable keyword in classes. The keyword mutable enables a const member function to change a variable. This explains the concept of logical const-ness of the object where the object changes in a way that it is not apparent through a public interface.

Here is the source code of the C++ program illustrates the concept of mutable keyword in classes. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Implement a Class with Mutable Members
  3.  */
  4. #include <iostream>
  5.  
  6. class A {
  7.     private:
  8.         int i;
  9.         mutable int j;
  10.     public:
  11.         A(int ii = 0, int jj = 1) : i(ii), j(jj) { }
  12.         void change() const;
  13.         void print();
  14. };
  15.  
  16. void A::change() const
  17. {
  18.     // Mutable variable 
  19.     j++;
  20. }
  21.  
  22. void A::print()
  23. {
  24.     std::cout << "A::i = " << i << std::endl
  25.               << "A::j = " << j << std::endl;
  26. }
  27.  
  28. int main()
  29. {
  30.     A a;
  31.  
  32.     std::cout << "Before A::change()" << std::endl;
  33.     a.print();
  34.     a.change();
  35.     std::cout << "After  A::change()" << std::endl;
  36.     a.print();
  37. }

$ a.out
Before A::change()
A::i = 0
A::j = 1
After  A::change()
A::i = 0
A::j = 2

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.