Mahbub
Mahbub

Reputation: 31

Method chaining in C++?

I did not understand the following code snippet from "Programming Principles and Practice" 2nd ed. by Bjarne Stroustroup article 13.3.

void Lines::draw_lines() const
{
    if (color().visibility())
    for (int i=1; i<number_of_points(); i+=2)
        fl_line(point(i–1).x,point(i–1).y,point(i).x,point(i).y);
}

I did not understand the color().visibility() part. What actually is this? I heard about method chaining though I am not fully understand this. Is this an example of such method chaining? I have seen in the wikipedia that, in a chained method the first function should return an object and the second function becomes the member function of that returned object by the first function. However, here in this example by Bjarne Stroustroup there is no instance before the color() function. How will this color() become a member function for an object as there is no instance to work on? Can anybody enlighten on this please?

Upvotes: 2

Views: 2228

Answers (2)

eerorika
eerorika

Reputation: 238361

Is this an example of such method chaining?

Typically, method chaining describes chained calls to member functions, which return the instance (by reference) on which they're called. But in this case, the first function appears to not be a member function of the instance that it returns. Otherwise the pattern is identical to method chaining.

However, here in this example by Bjarne Stroustroup there is no instance before the color() function.

And thus you can deduce that color is either a non-member function, or a member of Lines in which case the instance is implicitly this. You can also deduce that it returns an instance to an object that does have a member function visibility. Of course, you don't need to do such deduction if you have the declaration of color available.

How will this color() become a member function for an object as there is no instance to work on?

It does not become a member function. If it's a member function of Lines, then it works on this, otherwise it is a free function and does not need an instance. In either case, it can return an unrelated instance of some type that has a member function by the name of visibility.

Upvotes: 2

songyuanyao
songyuanyao

Reputation: 172934

there is no instance before the color() function

It doesn't matter. color() might be a member function of Lines (with instance this), or a global free function (without instance at all).

And then as you said, the second function visibility() supposed to be the member function of that returned object by the first function color().

Upvotes: 4

Related Questions