Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: Method Chaining

📅 2006-Nov-08 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp ⬩ 📚 Archive

I recently had to do this to an object:

Fbo f;

In this case, calling so many functions was inevitable since I was setting this particular object to non-default values. That is okay, but I would like to do the above like this:

Fbo f;

This is called method chaining and is a neat C++ trick.

All that is needed for this to work is that every function that is involved in the chaining (except the rightmost one) needs to return *this at the end of the call. For example:

class Fbo
    Fbo& setType(GLenum type)
        _type = type;
        return *this;