< Previous | Contents | Next >

Defining Constant Member Functions

A constant member function cant 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 dont need to change any data members in a member function, then its 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

image

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.

image


You can declare a constant member function by putting the keyword const at the end of the function header. Thats 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() cant 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 doesnt need to modify any data member. Generally, Get member functions can be defined as constant.