I have a question that is similar to the question that was asked here: How does "this" cascading work?
Suppose I have the following code:
#include <iostream>
using namespace std;
class Time
{
public:
Time( int = 0, int = 0, int = 0 );
Time setHour( int );
Time setMinute( int );
void print( void );
private:
int hour;
int minute;
};
Time::Time(int hr, int mn, int sc)
{
hour = hr;
minute = mn;
}
void Time::print( void )
{
cout << "hour = " << hour << endl;
cout << "minute = " << minute << endl;
}
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;
}
int main()
{
cout << "Hello, world!" << endl;
Time t;
t.setHour( 10 ).setMinute( 25 );
t.print();
}
Then, it is clear that the function setMinute( 25 ) is not running on the Time object t. Note that the functions setHour and setMinute do not return references to Time objects.
What is happening after t.setHour( 10 ) executes? Does the function setHour somehow return a "copy" of the object t, and setMinute( 25 ) is running on the copy? I have compiled the program with -Wall and no errors or warnings are returned.
Thanks for your assistance.