Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the use of *this in combine function given below

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading