Function Chaining

I first learned about this through CS247.

Method chaining method returns a reference to the owning object so that another method can be called.

It enables things like this:

cin >> x >> y >> z;
x = y = z;

Direction of chaining

Notice that some chaining methods evaluate from right to left (such as operator=), whereas other chaining methods evaluate from left to right (ex: operator>>).

a = b = c = d = e; // Evaluates right to left, returns the value that was set -> d=e executes first. Returns ref to do
 
// simplifies to a = b = c = d;
// simplifies to a = b = c;
// simplifies to a = b;
// simplifies to a;

Implementing Chaining

For classes to implement chaining, you should return *this.

  • the return type is a reference &, so it calls the function recursively
class Rational {
	...
	public:
		Rational& operator=(const Rational& rhs) {
			num = rhs.num;
			denom = rhs.denom;
			return *this;
		}
}

Another example

Node& Node::operator=(const Node& other) {
	if (this == &other) return *this;
	Node* temp = other.next ? new Node{*(other.next)} : nullptr;
	data = other.data;
	delete next;
	next = temp;
	return *this;
}

Chaining with operator>>

istream& operator>>(istream& in, Rational& r) {
	in >> r.num;
	in >> r.denom;
	return in;
}