Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method chaining including class constructor

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.

like image 684
jena Avatar asked May 20 '10 19:05

jena


People also ask

How are constructors implemented in chaining?

Constructor chaining can be done in two ways: Within same class: It can be done using this() keyword for constructors in the same class. From base class: by using super() keyword to call the constructor from the base class.

What does this method mean in constructor chaining concept?

Answer: Constructor chaining is the process of calling one constructor from another constructor with respect to current object. Constructor chaining can be done in two ways: Within same class: It can be done using this() keyword for constructors in same class.

Can you call a constructor in a method in the same class?

No, you cannot call a constructor from a method.

Why do we need constructor chaining?

Need for Constructor Chaining in Java Constructor Chaining in Java is used when we want to pass parameters through multiple different constructors using a single object. Using constructor chaining, we can perform multiple tasks through a single constructor instead of writing each task in a single constructor.


2 Answers

Try

// creates a temporary object
// calls bar then baz.
Foo().bar().baz();
like image 147
Martin York Avatar answered Sep 18 '22 17:09

Martin York


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

Foo foo = Foo().bar().baz();
like image 24
ablaeul Avatar answered Sep 20 '22 17:09

ablaeul