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;
f.setType(GL_FLOAT);
f.setFormat(GL_RGB);
f.setIntFormat(GL_RGB32F_ARB);
f.init();

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;
f.setType(GL_FLOAT).setFormat(GL_RGB).setIntFormat(GL_RGB32F_ARB).init();

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;
    }
};

© 2023 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 Mastodon📧 Email