< Previous | Contents | Next >
A constant member function can’t modify a data member of its class or call a non-constant member function of its class. Why restrict what a member function can do? Again, it goes back to the tenet of asking only for what you
Using Static Data Members and Member Functions 269
need. If you don’t need to change any data members in a member function, then it’s a good idea to declare that member function to be constant. It protects you from accidentally altering a data member in the member function, and it makes your intentions clear to other programmers.
Tra p
Okay, I lied a little. A constant member function can alter a static data member. You’ll learn about static data members a bit later in this chapter, in the “Declaring and Initializing Static Data Members” section. Also, if you qualify a data member with the mutable keyword, then even a constant member function can modify it. For now, though, don’t worry about either of these exceptions.
You can declare a constant member function by putting the keyword const at the end of the function header. That’s what I do in Critter with the following line, which declares GetHunger() to be a constant member function.
int GetHunger() const;
This means that GetHunger() can’t change the value of any non-static data member declared in the Critter class, nor can it call any non-constant Critter member function. I made GetHunger() constant because it only returns a value and doesn’t need to modify any data member. Generally, Get member functions can be defined as constant.