Method Chaining (Returning *this)

Hard Encapsulation, Access Specifiers & The this Pointer PRO
🔒 Login to Unlock

Problem Statement

Create a `Builder` class with a private `int value = 0`. Implement two methods: `add(int v)` and `sub(int v)`. Both must return a reference to the current object (`Builder&`) by returning `*this`. Add a `print()` method to output ‘Value: [value]’. Read two integers, add the first, subtract the second using method chaining: `b.add(x).sub(y).print();`.

Input Format

Two space-separated integers.

Output Format

Print the chained math result.

Constraints

None

Sample Input

10 3

Sample Output

Value: 7

Explanation

Returning a dereferenced `this` pointer as a reference enables fluent interface design, where multiple method calls can be chained sequentially on a single line.

Starter Code

#include <iostream>

class Builder {
    // Implement value, add, sub, and print
};

int main() {
    // Read input and chain methods on a single line
    return 0;
}

Limits

  • Time Limit: 1s
  • Memory Limit: 256MB

Embedded C Programming

Updated: March 15, 2026
Intermediate

Embedded systems rely on efficient low-level programming to interact directly with hardware. In this course, you will learn how to write practical Embedded C programs used in real microcontroller-based systems. Rather than focusing only on theory, this course follows a practice-driven approach. Each lesson includes hands-on coding exercises that simulate real firmware development tasks used