-1

I have a class method that needs to know the value of a variable named mode which takes the values 1 an 0 and is a private attribute of the class. I want to write a setter function that can change mode to 1 or 0. However, I must use an enum to determine the new value that I should set mode to: enum sequence {error=0,active =1}; I want sequence to be an attribute (I was hoping to make it private) of the class. How can I write a setter function that takes as input active or error and sets the value of mode accordingly. Here is the basic structure of my code:

#include <iostream>
class Blink{

public:

  void setter(...){
  
     
}
  
private:()
  int mode = 0;
  enum sequence {error = 0, active = 1};

};
Blink b;
int main() {
   
  b.setter(active);
  
  
}

PS: I'm having a hard time coming up with a good title for this question, suggestions are appreciated!

Sylvassi
  • 3
  • 2
  • 2
    Since the enumeration is `private`, you can't use it from "outside the class". If you make it `public` then you use it with the scope operator `::`, as in `Blink::active`. – Some programmer dude Mar 06 '22 at 08:26
  • Maybe my title was misleading but I was hoping to keep sequence private and only change it through the setter method. I wouldn't be changing it outside of the scope of the class. – Sylvassi Mar 06 '22 at 08:39
  • Your call to the setter in `main()` is already outside the scope of the class. – ypnos Mar 06 '22 at 09:35
  • 2
    One option would be to have *two* setters, `setActive()` and `setError()`. There is absolutely no rule that we must have one setter per member variable. (Often *none* is the correct number :-) – BoP Mar 06 '22 at 09:52

1 Answers1

0

It's pretty straight forward. This is how I would do it in C++11 and above:

class Blink {

public:
  enum class Sequence { Error, Active };
  
  void setter(Sequence s) {
    if (s == Sequence::Active) {
      mode = 1;
    } else {
      mode = 0;
    }
  }
  
private:
  int mode = 0;
};

Blink b;

int main() {
  b.setter(Blink::Sequence::Active);
}

The main difference is that Sequence is declared publicly. Note that mode is still a private variable so there is no harm. Sequence becomes part of the public interface because it needs to be understood from outside.

The second change is that I use enum class. Yes, you could also use a plain enum that implicitely casts to the integer, but see Why is enum class preferred over plain enum? In this simple example, I would instead use private member Sequence mode = Sequence::Error; instead of int mode = 0;.

ypnos
  • 50,202
  • 14
  • 95
  • 141