Mechanical Demonstration of a mutable Data Member

Figure 21.2 demonstrates using a mutable member. The program defines class TestMutable (lines 7–21), which contains a constructor, function getValue and a private data member value that’s declared mutable. Lines 15–18 define function getValue as a const member function that returns a copy of value. Notice that the function increments mutable data member value in the return statement. Normally, a const member function cannot modify data members unless the object on which the function operates—i.e., the one to which this points—is cast (using const_cast) to a non-const type. Because value is mutable, this const function can modify the data.

 1   // Fig. 21.2: fig21_02.cpp ...

Get C++11 for Programmers, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.