Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this chaining method not working?

Tags:

c++

It's a simple counter. The method add is being called to increment the private variable count by 1 by default. I am returning the Counter class from the function so that it may be chained, but when I look at the output, it gives me 1 when I expect it to be 3 because I called add three times.

#include <iostream>
#include <vector>

using std::cout;

class Counter {
    public:
        Counter() : count(0) {}

        Counter add() {
            ++count; return *this;
        }

        int getCount() {
            return count;
        }
    private:
        int count;
};

int main() {

    Counter counter;

    counter.add().add().add();

    cout << counter.getCount();

}
like image 789
template boy Avatar asked Aug 17 '12 19:08

template boy


People also ask

What is method chaining Why is it bad?

The drawback to self-referential method chaining is that you communicate that multiple method calls are required to do something, and that each call builds off the last. If this is not true, then method chaining could be communicating the wrong thing to other programmers.

How do you do chaining method?

Method Chaining is the practice of calling different methods in a single line instead of calling other methods with the same object reference separately. Under this procedure, we have to write the object reference once and then call the methods by separating them with a (dot.).

What is method chaining in C++?

Method chaining in C++ is when a method returns a reference to the owning object so that another method can be called.


1 Answers

The whole idea of chaining idiom is based on accessing the same, original object in each chained call. This is usually achieved by returning a reference to the original object from each modifying method. This is how your add should have been declared

    Counter &add() { // <- note the `&`
        ++count; return *this;
    }

That way, each application of add in your chained expression will modify the same, original object.

In your original code, you return a temporary copy of the original object from add. So, each additional application of add (after the first one) works on a temporary copy, modifies that copy and produces yet another temporary copy. All those temporary copies disappear without a trace at the end of the full expression. For this reason, you never get to see the effects of any add calls besides the very first one.

like image 119
AnT Avatar answered Nov 06 '22 21:11

AnT