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

Posted by – November 18, 2005

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;
public:
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);
x1.f();
x2.f();
}

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
{
public:
bool GetFlag() const
{
m_accessCount++;
return m_flag;
}
private:
bool m_flag;
mutable int m_accessCount;
};
int main()
{
}
WeChatWhatsAppEvernoteLineInstapaperFacebookTwitterGoogle+LinkedInBaidu

Leave a Reply

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