Reputation: 51
In the class below. I am struggling to understand why you would return a reference to the class from a member function.
For example setInterval() initializes the member variable 'interval. Could anybody explain the advantage of returning a reference of the class type?
Is it a reference to *this?
template <class Tx, class Ty = Tx>
class FitFunction {
std::pair<Tx, Tx> interval;
uint8_t var = 0;
public:
FitFunction& setInterval(Tx minX, Tx maxX);
};
Upvotes: 0
Views: 89
Reputation: 211670
That's not a reference to the class, it's a reference to an instance of the class.
This is typical in functions you want to be chainable, as in:
FitFunction ff;
ff.setInterval(...).setSomethingElse(...);
Where the idea is that function does a return *this
at the end, so yes, effectively a reference to that.
You'll see this approach used a lot more in things like operator<<
for streams which is chained by design.
Upvotes: 7