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.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Practice Computer Science MCQs
- Check Programming Books
- Practice Programming MCQs
- Check C++ Books
- Apply for Computer Science Internship