Function Chaining?

Can someone point me into the direction of where I can learn how to do something like this:


func1().func2().func3().....

Thank you
Well, each function returns an object that has this member function(s).
What does '.' represent in the chain. Multiplication?
It's the class member operator, just like in str.empty().
int p = pMember->getINode()->getRef() * 3;

A working example.

Ah well, in that case the answer is yes, certainly where pointers are involved.

Member and Node are two interrelated classes with getNode and getRef associated getters
He wants to apply several methods of single class to itself. It is a well known paradigm actively used in several languages (C# as one example)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class foo
{
  private:
    int x;
    int y;
  public:
    foo& setx(int x_)
    {   x = x_;
        return *this; }
    foo& sety(int y_)
    {   y = y_;
        return *this; }
    foo& print()
    {std::cout << x << ' ' << y;
     return *this;}
};

int main()
{
    foo bar;
    bar.setx(1).sety(2).print();
}
1 2
EDIT: Another example of function chaining allow you to write std::cout << x << ' ' << y; instead of
1
2
3
std::cout << x;
std::cout << ' ';
std::cout << y;
Last edited on
#include <iostream>

;-)
http://www.parashift.com/c++-faq/method-chaining.html

It chains these method calls, which is why this is called method chaining.

The first thing that gets executed is object.method1(). This returns some object, which might be a reference to object (i.e., method1() might end with return *this;), or it might be some other object. Let's call the returned object objectB. Then objectB becomes the this object of method2().

The most common use of method chaining is in the iostream library. E.g., cout << x << y works because cout << x is a function that returns cout.
Just keep the life time of the objects involved in mind when you are doing this. Most of the time it will be scenarios like what has been listed and so it won't matter, but stuff like this:
 
HANDLE hSubObject = MyObject.CreateCPPSubObject().GetCPPSubObjectHandle();

Is generally a bad idea since the intermediate object would be destroyed and that would make hSubObject invalid (assuming the sub object has a destructor).

Last edited on
Is generally a bad idea since the intermediate object would be destroyed

Example from the standard library I see often:
1
2
3
std::ostringstream s;
//...
s.str().c_str(); //UB! 
Topic archived. No new replies allowed.