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 am not an expert in C++, so can any one explain what am I missing?
>Solution :
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.