DEV Community

Cover image for Method Chaining in C++
Rishav Kapil
Rishav Kapil

Posted on

1

Method Chaining in C++

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:

  1. Methods should return a reference to the object they belong to (typically *this in C++).
  2. 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;
    }
Enter fullscreen mode Exit fullscreen mode
void print()
    {
        cout << "Lenght : "  << length << endl;
        cout << "Width : " << width << endl;
        cout << "Colour : " << color << endl;
    }
Enter fullscreen mode Exit fullscreen mode
Rectangle& setColor(string set_color){
        color = set_color;
        return *this;
    }
Enter fullscreen mode Exit fullscreen mode
Rectangle& setLength(int set_length){
        length = set_length;
        return *this;
    }
Enter fullscreen mode Exit fullscreen mode

};

int main()
{
    Rectangle r1(4,5,"red");
    r1.setColor("orange").setLength(10);
    r1.print();
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

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 :)

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

đź‘Ą Ideal for solo developers, teams, and cross-company projects

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay