Kyle Blue Kyle Blue - 1 year ago 71
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:


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 Source

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:


which is equivalent with:


(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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download