What does it mean to return a class object to a member function?

I'm new to C ++ programming, so sorry if this is stupid. I am working on a C ++ programming tutorial, and there is something that I just can't omit. Take this function, for example:

Sales_data& Sales_data::combine(const Sales_data &rhs) { units_sold += rhs.units_sold; revenue += rhs.revenue; return *this; } 

And we called the function using:

 total.combine(trans); 

I get that the units sold and the revenue in the common object will be combined with the units in the trans object, working like the compound assignment operator (+ =).

I understand that this will return the full object, but I do not get what the general object returns ...

+5
source share
4 answers

Returning by reference (to the called object) means that you can bind calls with one string code; all these calls will be associated with the same object:

 total.combine(trans).combine(trans2).combine(trans3); 

which is equivalent to:

 total.combine(trans); total.combine(trans2); total.combine(trans3); 

(Of course, this does not mean that you should call the same method, you can mix with other methods with a similar characteristic.)

This idiom is often used in implementations of operators such as operator= , operator<< , operator>> , etc., which can also be called with a chain:

 a = b = c; cout << a << b << c; 
+9
source

It returns a reference to itself, this allows a chain of methods. For example, suppose you have 2 Sales_data objects, and you want to combine both of them, you can chain the calls:

 Sales_data s1, s2, total; //stuff.. total.combine(s1).combine(s2); 

Since you are returning a link, this allows you to change the total object between calls, which is why it is called a β€œchain”.

+7
source

In this example, you are returning a link to total , which allows us to use the expression total.combine(trans) as a modified total object.

For example, if operator<< overloaded for Sales_data , we can simply combine and print the modified totals as follows:

 std::cout << total.combine(trans); 

or we can bind methods if we want to combine many times for the same object:

 total.combine(trans).combine(trans1); 

In this example, total merged, and the same total object is returned, and we can again merge with the already modified object.

This is a good template to simplify the code when you need to use a modified object in the same expression.

+3
source

The above example uses the character and the reference character after the class. This allows you to pass a reference to an existing class object using * this. All refunds of a reference means that you are returning a pointer to your object on the stack. This is useful syntax for chain calls.

 total.combine(trans).combine(trans2).combine(trans3); 
+3
source

Source: https://habr.com/ru/post/1260595/


All Articles