OOPortal OOPortal


C++ Class Construct  «Prev 

Defining static and const member functions

Use const whenever possible, including when modifying member functions. The use of const allows the compiler to test additional features of your code. It is part of the static type-safety of the C++ language. It is also useful documentation and potentially an aid in optimization. Using the class name with the scope resolution operator instead of the variable name with the dot operator makes it clear that the variable being referenced is static.
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.
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.

// constant_member_function.cpp
class Date{
public:
  Date( int mn, int dy, int yr );
  int getMonth() const;     // A read-only function
  void setMonth( int mn );   // A write function; can't 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
}
int main()
{
   Date MyDate( 7, 4, 1998 );
   const Date BirthDate( 1, 18, 1953 );
   MyDate.setMonth( 4 );    // Okay
   BirthDate.getMonth();    // Okay
   BirthDate.setMonth( 4 ); // C2662 Error
}