What is method chaining ?
Method chaining is a programming technique where multiple method calls are executed sequentially on the same object, all in a single statement. Each method in the chain returns the object itself (usually *this), allowing the next method to be called on the same object without needing to reference it again.
How It Works
To enable method chaining:
- Methods should return a reference to the object they belong to (typically *this in C++).
- Each method can then be called on the returned reference, forming a chain.
Example
Lets take an example of "Rectangle class"..
class Rectangle{
public:
int length;
int width;
string color;
Rectangle(int set_length , int set_width , string set_color){
length = set_length;
width = set_width;
color = set_color;
}
void print()
{
cout << "Lenght : " << length << endl;
cout << "Width : " << width << endl;
cout << "Colour : " << color << endl;
}
Rectangle& setColor(string set_color){
color = set_color;
return *this;
}
Rectangle& setLength(int set_length){
length = set_length;
return *this;
}
};
int main()
{
Rectangle r1(4,5,"red");
r1.setColor("orange").setLength(10);
r1.print();
return 0;
}
without method chaining we have to repeat the object like
object1.method1();
object1.method2();
object1.method3();
here the object is getting repeated again and again but with the help of method chaining we can resolve this issue
with method chaining
object1.method1().method2().method3()
here when the method1 is executed it will return the object itself which will help in the execution of method2 and so on.
I hope you got my point :)
Top comments (0)