Method chaining is a mechanism of calling multiple functions (methods) in a single statement. It helps us reduce number of lines in the code and increase code elegancy. And in most cases it increases the code readability.
class c1 {
public:
void setX(int v) {
x = v;
}
void setY(int v) {
y = v;
}
void print() {
cout << "X = " << x << endl;
cout << "Y = " << y << endl;
}
private:
int x;
int y;
};
Here in the class, c1, we have 3 member functions. First two functions set two variables – x and y. And the third one prints them.
We can call these functions one after another using an object like this.
c1 obj;
obj.setX(10);
obj.setY(20);
obj.print();
But in C++, like many other object oriented programming languages, we can call all 3 functions in one statement.
obj.setX(10).setY(20).print();
To do this, we’ll need to change the functions a little bit.
Right now the functions are not returning anything. They need to return the reference of the current object. How can we get the reference of the current object? In C++, there is a special pointer called this that allows us to get hold of the current object. Using this pointer, we can return a reference of the object from a member function. The next function will be called in the context of the returned object reference returned from the previous function.
Here is the modified code.
#include <iostream>
using namespace std;
class c1 {
public:
c1 &setX(int v) {
x = v;
return *this;
}
c1 &setY(int v) {
y = v;
return *this;
}
c1 &print() {
cout << "X = " << x << endl;
cout << "Y = " << y << endl;
return *this;
}
private:
int x;
int y;
};
int main() {
c1 obj;
obj.setX(10).setY(20).print();
return 0;
}
$ g++ -o test test.cpp
$ ./test
X = 10
Y = 20
We can the same functions multiple times also like this.
obj.setX(10).setY(20).print().setX(100).setY(200).print();
$ ./test
X = 10
Y = 20
X = 100
Y = 200
Method chaining can make debugging difficult. Like, putting a break point for a particular function call might not be convenient, if many functions are called in a single statement.