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.
/*
* C++ Program to Implement a Class with Mutable Members
*/
#include <iostream>
class A {
private:
int i;
mutable int j;
public:
A(int ii = 0, int jj = 1) : i(ii), j(jj) { }
void change() const;
void print();
};
void A::change() const
{
// Mutable variable
j++;
}
void A::print()
{
std::cout << "A::i = " << i << std::endl
<< "A::j = " << j << std::endl;
}
int main()
{
A a;
std::cout << "Before A::change()" << std::endl;
a.print();
a.change();
std::cout << "After A::change()" << std::endl;
a.print();
}
$ 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.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy Computer Science Books
- Apply for Computer Science Internship
- Practice Programming MCQs
- Buy C++ Books
- Practice Computer Science MCQs