Aage Torleif
Aage Torleif

Reputation: 2013

Can this JS syntax be mimicked in C++

So I write a lot of JS and I'm a fan of this feature of the syntax. I'm not sure what this would be called, but below is an example.

object.function1().function2().function3()

I'm aware JS can do this because everything is treated as a first class object. But I was wondering if this is possible in C++? also what would a short example of that be?

Upvotes: 1

Views: 61

Answers (2)

Omer
Omer

Reputation: 704

You mean something like this:

class A{
public:
    A& foo(){ return *this; };
    A& bar() { return *this; };
};

and then

A a;
a.foo().bar();

Upvotes: 3

David G
David G

Reputation: 96810

In C++, this is a pointer to the instance; you have to dereference it in order to return the instance:

return *this;

And if you want to avoid a copy so you can mutate the same object, you would return a reference. Here's an example:

struct X
{
    X& f() { std::cout << ++x << std::endl; return *this; }                    /*
    ^^                                      ^^^^^^^^^^^^^                      */
private:
    int x = 0;
};

int main()
{
    X x;
    x.f().f().f(); // 1 2 3
}

Upvotes: 4

Related Questions