Just as you can use the const keyword when declaring a variable, you can also use it when declaring an object. Such a declaration means that the object is a constant, and none of its data members can be modified. For example:
const Date birthday( 7, 4, 1776 );
This declaration means that the value of birthday cannot be changed.
When you declare a variable as a constant, the compiler can usually identify operations that would modify it (such as assignment), and it can generate appropriate errors when it detects them. However, this is not true when you declare an object as a constant. The compiler can't tell whether a given member function might modify one of an object's data members, so it plays it safe and prevents you from calling any member functions for a const object.
However, some member functions don't modify any of an object's data members, so you should be able to call them for a const object. If you place the const keyword after a member function's parameter list, you declare the member function as a read-only function that doesn't modify its object. The following example declares some of the Date class's member functions as const.
class Date
{
public:
Date( int mn, int dy, int yr ); // Constructor
// Member functions:
int getMonth() const; // Get month - read-only
int getDay() const; // Get day - read-only
int getYear() const; // Get year - read-only
void setMonth( int mn ); // Set month
void setDay( int dy ); // Set day
void setYear( int yr ); // Set year
void display() const; // Print date - read-only
~Date(); // Destructor
private:
int month, day, year; // Private data members
};
inline int Date::getMonth() const
{
return month;
}
// etc...
The various get functions and the display function are all read-only functions. Note that the const keyword is used in both the declaration and the definition of each member function. These functions can be safely called for a constant object.
With the Date class modified in this way, the compiler can ensure that birthday is not modified:
int i;
const Date birthday( 7, 4, 1776 );
i = birthday.getYear(); // Legal
birthday.setYear( 1492 ); // Error: setYear not const
The compiler lets you call the const member function getYear for the birthday object, but not the function setYear, which is a non-const function.
A member function that is declared with const cannot modify any data members of the object, nor can it call any non-const member functions. If you declare any of the set functions as const, the compiler generates an error.
You should declare your member functions as const whenever possible. This allows people using your class to declare constant objects.