I have a class that has two states, and different members are only applicable in one state or the other.
Which is the better practice:
- Option 1: constructor initializes only the members relevant to the first (initial) state
- Option 2: initialize every member, even if that means inventing "uninitialized" values for members?
E.g.
class Foo {
public:
  enum State { A, B };
  // Constructor
  // Option 1: Only initialize first state
  Foo(int a1) : _state(A), _a1(a1) {}
  // ... or ... 
  // Option 2: initialize every member
  Foo(int a1) : _state(A), _a1(a1), b1(-1), b2(-1) {}
  State getState() const { return _state; }
  // Only applicable if State is A
  int getA1() const { return _a1; } // Might also add assert that State is A
  // Only applicable if State is B
  int getB1() const { return _b1; } // Might also add assert that State is B
  int getB2() const { return _b2; } // Might also add assert that State is B
private:
  State _state;
  int _a1;
  int _b1;
  int _b2;
};
 
     
     
     
     
     
    