0
Sales_data& Sales_data::combine(const Sales_data &rhs)
{
    units_sold += rhs.units_sold; // add the members of rhs into
    revenue += rhs.revenue; // the members of ''this'' object
    return *this; // return the object on which the function was called
}

I saw above method somewhere, and I am confused why *this pointer is being returned? Even though without it (using void return type) function does the same thing. I know how *this pointer works but I was confused why *this pointer was used in above context.

I am not an expert in C++, so can any one explain what am I missing?

Saad Khan
  • 27
  • 5
  • 1
    Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to search and then research and you'll find plenty of related SO posts for this. – Jason Mar 20 '23 at 10:14

2 Answers2

5

It allows method chaining, e.g. if you have multiple sales data objects that you want to combine, you can write

all_data.combine(alices_data).combine(charlies_data).combine(bobs_data);
Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157
  • 1
    Thank you very much for your answer, so alices_data will combine first, then charlies_data and then bobs_data right? – Saad Khan Mar 20 '23 at 08:44
  • 1
    Exactly, alices_data will combine first, then charlies_data and then bobs_data. – André Mar 20 '23 at 08:46
  • 1
    And for a more concise explanation of _why_ it's evaluated in that order, see the table and its description in [C++ Operator Precedence](https://en.cppreference.com/w/cpp/language/operator_precedence) and note that the operator associativity for [member access](https://en.cppreference.com/w/cpp/language/operator_member_access#Built-in_member_access_operators) is left-to-right. – paddy Mar 20 '23 at 08:48
4

The * operator is just dereferencing the address of the this-pointer. This way you get the desired return type, which is a reference to your Sales_data class. An educated guess would be that the implentation is this way to chain function calls, e.g. by a.combine(b).combine(c).combine(d); etc.

With the void interface you were referring to you would have to write:

a.combine(b);
a.combine(c);
a.combine(d);

I would say in the end it is personal preference whether you go for one or the other implementation.

André
  • 303
  • 1
  • 8
  • 2
    Historical footnote, `this` is a pointer to the object rather than a reference to the object because `this` was introduced very early in the language, and references were added several years later. – Eljay Mar 20 '23 at 11:04