randy
randy

Reputation: 165

return function call by reference

enter image description here

I am reading the textbook, then I encounter the function as above "Sales_data::combine()".

If I do

Total.combine(trans);

in which Total and trans are Sales_data, after this function call, would the object Total be changed? And what's the point of returning the *this?

Upvotes: 0

Views: 77

Answers (1)

Tony Delroy
Tony Delroy

Reputation: 106068

after this function call, would the object Total be changed?

It will be changed if trans.units_sold and/or trans.revenue is not zero, as the same fields in Total are affected by the += statements in the function implementation.

And what's the point of returning the *this?

It lets you chain further calls to member functions, so you could do something like:

Total.combine(trans1).combine(trans2);

That would combine values from both trans1 and trans2 into Total.

If Sales_data has other functions, you could use the return value of combine to access them too. For example, if there's an operator<<(std::ostream&, const Sales_data&) function for streaming a Sales_data object, you could write...

std::cout << Total.combine(trans1) << '\n';

...which would merge the values from trans1 into Total before printing the updated values from Total.

Upvotes: 6

Related Questions