A const object can only call const function

来源:互联网 发布:淘宝服装店铺定位 编辑:程序博客网 时间:2024/05/21 19:27

consider the following class
//=========================================================
class cal_date
{
  public:
    bool is_leap_year( void ) const ;

  private:
    int year ;
    int month ;
    int day ;
 
    bool is_valid_date( void ) ;
 } ;

bool cal_date::is_leap_year(void) const
{
  bool IsLeapYear = false ;
  if( is_valid_date() )
  {
    // code to check if it's a leap year
    // ....
    return ( IsLeapYear ) ;
  } // end if
} // end is_leap_year
//=========================================================

There's something wrong with member function "is_leap_year()". The "is_leap_year()" is a const function which cannot change the properties of 'cal_date' class. On the contrary, "is_valid_date" is not a const function which can modify the properties of 'cal_date' class. Thus, a const function calling a non-const function can not make sure that the properties of a class won't be modified.

A solution to this problem is to modify the non-const function to a const function. For example, the member function "is_valid_date()" can be rewritten as following:

//=========================================================
//    bool is_valid_date( void ) const ;
//=========================================================

Now we can call "is_valid_date()" in the function "is_leap_year()".

原创粉丝点击