Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 396
Sam Avatar asked Dec 19 '25 02:12

Sam


1 Answers

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.

like image 91
AnT Avatar answered Dec 20 '25 16:12

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!