The const Keyword





Compile-time Errors

Suppose we have the declaration:

const DayOfYear jan1st( 1, 1);

followed by an invocation of a mutator member function:

jan1st.Set(1, 2) ;

We would get a compile-time error message like:

myfile.cpp: In function `int main()': myfile.cpp:20: passing `const DayOfYear' as `this' argument of `void DayOfYear::Set(int, int)' discards qualifiers



const Member Functions





const Member Function Pledge

I promise not to modify the object which calls me
(either directly or indirectly), and therefore
I may be called by const objects.





Rules of Engagement

  1. const member functions may be invoked for const and non-const objects.

  2. non-const member functions can only be invoked for non-const objects.

  3. If a non-const member function is invoked on a const object, it is a compiler error.

  4. non-const objects may be used for const and non-const parameters

  5. const objects may only be used for const parameters

  6. const methods cannot invoke non-const methods




Subtle Error

This common mistake leads to a compiler error. Do you see why?

int DayOfYear::GetDay ( ) const { if (m_day < 1 ) Set( m_month, 1 ); return m_day; }



Another Subtle Error

Another common mistake leads to a compiler error.

void Bob (const DayOfYear& doy) { OutputDayOfYear ( doy ); cout << "Please enter your birth month and day \n"; int birthMonth, birthDay; cin >> birthMonth >> birthDay; doy.Set( birthMonth, birthDay ); }



More Rules of Engagement

Objects are usually passed by reference.




const objects non-const objects
Call const methods Yes Yes
Call non-const methods NO Yes
Pass as const parameter Yes Yes
Pass as non-const parameter NO Yes




The Importance of being const





Class Design & const