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 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.
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.).
Method chaining in C++ is when a method returns a reference to the owning object so that another method can be called.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With