C++ Tips from Thinking in C++(3)

This entry is continued from C++ Tips from Thinking in C++(2)

6. Const functions can only be used by const objects. p359
If you declare a member function const, you tell the compiler the function can be called for a const object. A member function that is not specifically declared const is treated as one that will modify data members in an object, and the compiler will not allow you to call it for a const object. It doesn’t stop there, however. The compiler forces you to reiterate the const specification when defining the function.
For example,

class X {
int i;
X(int ii);
int f() const;
X::X(int ii) : i(ii) {}
int X::f() const { return i; }
int main() {
X x1(10);
const X x2(20);

What if you want to create a const member function, but you’d still like to change some of the data in the object?If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function. For example, the following code will compile without error because m_accessCount has been declared to be mutable, and therefore can be modified by GetFlag even though GetFlag is a const member function.

class X
bool GetFlag() const
return m_flag;
bool m_flag;
mutable int m_accessCount;
int main()

Leave a Reply

Your email address will not be published. Required fields are marked *