The 4 ways to use

const

in C++

1/

const int innings = 9; // innings is a constant variable that can't be changed

2/ as used in one apstring overloaded operator member function prototype:

const apstring & operator = (char ch); // assign ch

the const here keeps the returned object from being modified within the "statement" where it is being returned, as in

apstring myInitial('M');

(myInitial = 'P') = 'G';

The assignment statement above is ambiguous and therefore disallowed by the use of const. The value returned as myInitial after the execution of the parentheses is 'P' but the use of const keeps it from being modified further when the second assignment operator is applied. Note however that using const this way does not prevent the following logic:

MyInitial = 'P';

MyInitial = 'G';

It is common and wise to use const in this way when overloading assignment and compound operators.

3/ as used to make a const member function as in:

int length() const; // number of chars

which prevents the programmer from accidentally changing the value of any member variables of the object within the length function. A careful programmer would never have to use const in this way since he/she would not write code within a member function that changes member variables unless he/she was sure that he/she means to do so. But, it is common and wise for programmers to use const to make "constant member functions" to avoid logic errors. A syntax error will result if you do accidentally try to modify member variables within a constant member function.

It is common to use const in this way in accessor functions whose only purpose is to "retrieve" data anyway.

4/ as used within the parameter list of a function. This is done in:

int find( const apstring & str ) const; // index of first occurrence of str

where the incoming, formal parameter str is being passed to the find member function by reference. Passing an apstring by reference is advisable because it is memory efficient and faster than passing a potentially large object by value. But, if the programmer really doesn't intend to modify the actual argument's value (like he would if he purposefully chose to pass by reference in order to change the actual parameters real value), he uses const in this way. Using const here will cause a syntax error if the code in his function accidentally modifies str (the formal parameter), thus providing a check against sloppy programming.