Search code examples
c++class-design

Can you chain methods by returning a pointer to their object?


My goal is to allow chaining of methods such as:

class Foo;
Foo f;
f.setX(12).setY(90);

Is it possible for Foo's methods to return a pointer to their instance, allowing such chaining?


Solution

  • For that specific syntax you'd have to return a reference

    class Foo {
    public:
    
      Foo& SetX(int x) {
        /* whatever */
        return *this;
      } 
    
      Foo& SetY(int y) {
        /* whatever */
        return *this;
      } 
    };
    

    P.S. Or you can return a copy (Foo instead of Foo&). There's no way to say what you need without more details, but judging by the function name (Set...) you used in your example you probably need a reference return type.