0

Hello im studing classes and i have the following code :

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

I would like to know why we use return *this, and Sales_Data &.

Arun A S
  • 6,421
  • 4
  • 29
  • 43
Geech
  • 47
  • 3

3 Answers3

7

Doing so you can run multiple combines in one statement:

Sales_Data d1, d2, d3;
d1.combine(d2).combine(d3);
Manuel Barbe
  • 2,104
  • 16
  • 21
6

You do this when you need to return a reference to yourself. You typically see it in operator overloading, so that the result can return itself:

Foo &operator=(const Foo &rhs)
{
  // Whatever...
  return *this;
}

By doing this it allow you to easily chain calls:

a=b=c;

Whereas if returned a pointer it would look messy.

It's also commonly used in fluid api design so that you can combine calls. Using your example you could write:

Sales_Data x,y,z;

x.combine(y).combine(z);

However, if does loose a bit of its elegance when you've got a pointer lurking around:

  Sales_Data *x=LoadSalesData();
  Sales_Data y,z;

  x->combine(y).combine(z);
Sean
  • 60,939
  • 11
  • 97
  • 136
3

You use *this to return a reference to current object.

This is usually useful to allow method chaining:

rhs1.combine(rhs2).combine(rhs3);

A well known example of this is the operator<< of streams, that returns a reference to the stream object to make concatenation of outputs possible.

std::cout << "first" << "second";
Paolo M
  • 12,403
  • 6
  • 52
  • 73