Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

A const function question for a beginner

class foo
{
public:

void z(foo f) const;
...
1 how to i read - this function.
2. and i guess it will be clear once i understand syntax, but can z alter the private member variables of the object that activates the function
thanks
[293 byte] By [msbs48] at [2007-11-11 7:18:52]
# 1 Re: A const function question for a beginner
void z(foo f) const; should be read like this:

a function z that returns void, and takes a foo object by value as its argument. z is a const function which means that it cannot change the state (value) of its object's members -- any of them, regardless of their access type. This answers your second questions but there's an exception to the rule: if a data member is declared mutable, z can change that member (mutable effetively overrides the const of a member function, allowing that function to change such a member).
Danny at 2007-11-11 21:02:25 >
# 2 Re: A const function question for a beginner
Is mutable a bad idea? Seems like more violation of design stuff like grabbing a pointer to private data.
jonnin at 2007-11-11 21:03:28 >
# 3 Re: A const function question for a beginner
It isn't necessarily bad, but you clearly don't want to declare every data member as mustable. Think of it as public: -- would you declare all members public? no way. But can you get along along without it? No way. So just like many other features, it solves certain design problems neatly when used properly. Notice that without mutable the programmer would be forced to declare member functions as non-const which is much worse.
Normally, mutable applies to local, internal bookkeeping stuff that a const member function needs to change (for example, a debugging counter that counts how many times the function is called) while maintaining the const guarantee of not changing the object's state, e.g., it doesn't resize a windows or appends data to a stream file.
Danny at 2007-11-11 21:04:33 >