◄Up► ◄Contents► ◄Index► ◄Back► ─────C/C++ Language───────────────────────────────────────────────────────── Declaring a member function with the const keyword specifies that the function is a "read-only" function that does not modify the object for which it is called. Declaring Constant Member Functions To declare a constant member function, place the const keyword after the closing parenthesis of the argument list. The const keyword is required in both the declaration and the definition. A constant member function cannot modify any data members or call any member functions that aren't constant. class Date { public: Date( int mn, int dy, int yr ); int getMonth() const; // A read-only function void setMonth( int mn ); // A write function; // cannot be const private: int month; }; int Date::getMonth() const { return month; // Doesn't modify anything } void Date::setMonth( int mn ) { month = mn; // Modifies data member } Declaring Constant Objects To declare a constant object, place the const keyword at the start of an object declaration: const Date birthday( 3, 4, 1985 ); You can only call constant member functions for a constant object. This ensures that the object is never modified. birthday.getMonth(); // Okay birthday.setMonth( 4 ); // Error You can call either constant or nonconstant member functions for a nonconstant object. You can also overload a member function using the const keyword; this allows a different version of the function to be called for constant and nonconstant objects. You cannot declare constructors or destructors with the const fkeyword. -♦-