#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;
}
Explanation & Logic Summary:
*this by reference means each call gives back the same object, allowing another method to be called immediately.*this, chaining wouldn’t be possible.👉 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).
Firmware Relevance & Real-World Context:
Fluent APIs are widely used in firmware configuration:
timer.setPrescaler(8).setPeriod(1000).start();
Input
Expected Output
1