#include <iostream>
using namespace std;
class Counter {
private:
int value;
public:
Counter() : value(0) {}
Counter& increment() {
value++;
return *this; // enable chaining
}
Counter& decrement() {
value--;
return *this; // enable chaining
}
int getValue() const {
return value;
}
};
int main() {
Counter c;
c.increment().increment().decrement();
cout << c.getValue();
return 0;
}
Solution Details
👉 In simple words:
Instead of writing:
c.increment();
c.increment();
c.decrement();
we can write:
c.increment().increment().decrement();
because each method returns the object itself (*this).
Significance for Embedded Developers
Fluent APIs are widely used in firmware configuration:
timer.setPrescaler(8).setPeriod(1000).start();
Input
Expected Output
1