I have the following class interface:
class Time
{
public:
Time( int = 0, int = 0, int = 0 );
Time &setHour( int );
Time &setMinute( int );
Time &setSecond( int );
private:
int hour;
int minute;
int second;
};
The implementation is here:
Time &Time::setHour( int h )
{
hour = ( h >= 0 && h < 24 ) ? h : 0;
return *this;
}
Time &Time::setMinute( int m )
{
minute = ( m >= 0 && m < 60 ) ? m : 0;
return *this;
}
Time &Time::setSecond( int s )
{
second = ( s >= 0 && s < 60 ) ? s : 0;
return *this;
}
In my main .cpp file, I have this code:
int main()
{
Time t;
t.setHour( 18 ).setMinute( 30 ).setSecond( 22 );
return 0;
}
How is it possible to chain these function calls together? I don't understand why this works.
The technique is called method chaining. In the example you've given, all the methods return the same object (this), so they all affect the same object. That's not uncommon, but it's useful to know that it doesn't have to be the case; some or all of the methods in the chain can return different objects. For example, you might also have methods like:
in which case you could say:
to get the name of day of the week. In that case,
t.date()
returns a Date object which is used in turn to calldayOfWeek()
.