A const object can only call const function

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()".

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值