views:

146

answers:

3

Hello,

I'm trying to implement method chaining in C++, which turns out to be quite easy if the constructor call of a class is a separate statement, e.g:

Foo foo;

foo.bar().baz();

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

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

I'm wondering now if this is actually 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 "fluent interfaces" in C++ (http://en.wikipedia.org/wiki/Fluent_interface#C.2B.2B) which seems to be exactly what I'm searching for. However, I get the same compiler error for that code.

Thanks in advance for any hint.

Best,

Jean

+8  A: 

Try

// creates a temporary object
// calls bar then baz.
Foo().bar().baz();
Martin York
although in this case, returning a reference to a temporary object is a bit dodgy ;-)
stefaanv
No its well defined here. As the temporary object remains valid until the end of the statement (the ';'). All is fare in love and temporaries.
Martin York
+1  A: 

No, the syntax for C++ variable declarations doesn't allow for that - either a variable name with an optional argument list, or an assignment operator and an expression.

Pete Kirkham
+5  A: 

You have forgotten the actual name for the Foo object. Try:

Foo foo = Foo().bar().baz();
ablaeul
Or you can save a (const) reference to the object rather than copying the temporary into a new variable.
Martin York