Can you bind the methods by giving a pointer to your object?

My goal is to allow chaining of methods like:

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

      

Is it possible for methods to Foo

return a pointer to their instance by allowing chaining like this?

+2


source to share


5 answers


For this particular syntax, you will need to return a link

class Foo {
public:

  Foo& SetX(int x) {
    /* whatever */
    return *this;
  } 

  Foo& SetY(int y) {
    /* whatever */
    return *this;
  } 
};

      



PS Or you can return a copy ( Foo

instead of Foo&

). It's impossible to tell what you want without details, but judging by the function name ( Set...

) you used in your example, you probably want a reference return type.

+10


source


Another example is Named Parameter Identifier .



+4


source


Yes it is possible. An example comon is operator overloading such as the + = () operator.

For example, if you have a class called ComplexNumber and want to do something like + = b, you can

ComplexNumber& operator+=(ComplexNumber& other){
     //add here
     return *this; 
}

      

In your case, you can use.

Foo& setX(int x){
//yada yada yada
return *this;
}

      

+3


source


Well, you can return an object from your own function in order to combine the functions together:

#include <iostream>
class foo
{
    public:
        foo() {num = 0;}
        // Returning a `foo` creates a new copy of the object each time...
        // So returning a `foo&` returns a *reference* to this, and operates on
        // the *same* object each time.
        foo& Add(int n)  
        {
            num += n;
            std::cout << num << std::endl;
            // If you actually DO need a pointer, 
            // change the return type and do not dereference `this`
            return *this;  
        }
    private:
        int num;
};

int main()
{
    foo f;
    f.Add(10).Add(5).Add(3);
    return 0;
}

      

What are the outputs:

$ ./a.out
10
15
18

      

+2


source


#include <iostream>

using namespace::std;

class Print
{
    public:
        Print * hello();
        Print * goodbye();
        Print * newLine();
};

Print * Print::hello()
{
    cout << "Hello";
    return this;
}
Print * Print::goodbye()
{
    cout << "Goodbye";
    return this;
}
Print * Print::newLine()
{
    cout << endl;
    return this;
}

int main (void)
{
    Print print;
    print.hello()->newLine()->goodbye()->newLine();

    return 0;
}

      

Output:

   Hello
   Goodbye

      

0


source







All Articles