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. }

advertisement
$ 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
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn