Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happens to the last return *this c++?

  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?

like image 505
user3348712 Avatar asked Mar 06 '14 19:03

user3348712


People also ask

What happens when we don't catch the returned value from a function?

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.

What happens if you call a function that has a return value but you don't save the return value in a variable?

nothing, the return value gets ignored.


1 Answers

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);
like image 114
Ben Voigt Avatar answered Sep 19 '22 20:09

Ben Voigt