Kyle Blue Kyle Blue - 5 days ago 6
C++ Question

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

I'm quite new to programming in C++ so sorry if this is stupid. I have been working through the c++ primer book, and there is something i just cant get my head around. 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 & revenue in the total object will be combined with that in the trans object, working much like the compound assignment operator (+=).

I get that this would return the total object, but I dont get what returning the total object means...

Answer

Returning by reference (to the object being called on) means you could chain the calls in one line code; because all these calls would be bound to the same object:

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

which is equivalent with:

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

(Of course it doesn't mean you have to call the same method, you could mix with other methods with similar characteristic.)

This idiom is often seen in the implementations of operators like operator=, operator<<, operator>> etc, which are also possible to be called with chaining:

a = b = c;
cout << a << b << c;
Comments