147. Method Chaining with this

#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:

  • Returning *this by reference means each call gives back the same object, allowing another method to be called immediately.
  • Without returning *this, chaining wouldn’t be possible.
  • This is a common pattern for building fluent APIs.

👉 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();
  • It makes configuration code clean, readable, and less error-prone.
  • The this pointer is the key enabler of this style.

     

 

 

Loading...

Input

Expected Output

1