LED RAII Controller

#include <iostream>
using namespace std;

class LEDController {
private:
    static int state;   // 0 OFF, 1 ON

public:
    LEDController() { state = 1; }     // ON when created (acquire)
    ~LEDController() { state = 0; }    // OFF when destroyed (release)

    static void print() {              // can be called without object
        cout <<"LED="<<state<<"\n";
    }
};

// define static member (and set initial value = 0)
int LEDController::state = 0;

int main() {
    int x;
    cin >> x;

    {
        LEDController led;   // LED ON here

        if (x == 1)
            LEDController::print(); 
             // prints 1
    // led destroyed here -> LED OFF automatically
    }
    LEDController::print();            // prints 0
    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

1

Expected Output

LED=1 LED=0