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();
}
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
addshould have been declaredThat way, each application of
addin 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 ofadd(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 anyaddcalls besides the very first one.