Why does this chaining method not work?

This is a simple counter. The method addis called to increment the private variable countby 1 by default. I am returning a class Counterfrom a function so that it can be bound, but when I look at the output, it gives me 1, when I expect it to be 3, because I called addthree 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();

}
+5
source share
1 answer

The whole idea of ​​a chain idiom is based on access to the same original object in every chain call. This is usually achieved by returning a reference to the source object from each modification method. That's how your addwas supposed to be announced

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

, add .

add. , add ( ) , . . add, .

+13

All Articles