Method chain including class constructor

I am trying to implement a chain of methods in C ++, which turns out to be quite simple if the call to the class constructor is a separate statement, for example:

Foo foo;

foo.bar().baz();

But as soon as the constructor call becomes part of the method chain, the compiler complains about the expectation of ";" in place of "." immediately after calling the constructor:

Foo foo().bar().baz();

Now I am wondering if this is possible in C ++. Here is my test class:

class Foo
{
public:
    Foo()
    {
    }

    Foo& bar()
    {
        return *this;
    }

    Foo& baz()
    {
        return *this;
    }
};

I also found an example for “free interfaces” in C ++ ( http://en.wikipedia.org/wiki/Fluent_interface#C.2B.2B ), which seems to be exactly what I'm looking for. However, I get the same compiler error for this code.

+5
3

Foo. :

Foo foo = Foo().bar().baz();
+8

Try

// creates a temporary object
// calls bar then baz.
Foo().bar().baz();
+11

No, the syntax of C ++ variable declarations does not allow this - either the name of the variable with an additional list of arguments, or the assignment operator, and expression.

+1
source

All Articles