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;
}
int main()
{
Time t;
t.setHour( 18 ).setMinute( 30 ).setSecond( 22 );
return 0;
}
I understand the cascaded member function call, but I don't understand how t.setHour( 18 ).setMinute( 30 ).setSecond( 22 ); is left hanging, doesn't it have to be assigned to something since it still returns *this after it's done cascading? Why is it ok to leave it like that?
The returned value simply gets ignored. If a function returns a class instance, the class instance gets destroyed, which results in an invocation of the class's defined destructor, or a default destructor.
nothing, the return value gets ignored.
The value of the expression which is used as a statement is discarded. It's the same thing that happens when you write
scanf("%d", &i);
You did know that scanf
has a return value, right? And so does ++i
in
for( int i = 0; i < 10; ++i )
And even
x = 5;
is throwing away the result of the expression.
There are lots of expressions and functions with return values that are only marginally useful. If you want to write the code in a way that makes it clear the return value is ignored intentionally and not by accident, cast to void:
(void) scanf("%d", &i);
This should silence compiler warnings about ignored return values.
These variations are also valid but a bit sillier:
(void)++i;
(void)(x = 5);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With