Search code examples
c++booleandeclare

problems declaring bool false in class


boolean.cpp:
Boolean::Boolean() : test1(false),test2(false)
{
}

void Boolean::exec() {
  test1 = true;
  test2 = true;
  if ((!test1) && (!test2))
     std::cout << "both test1 && test2 are false" << std::endl;
  else
     std::cout << "test1 is " << test1 << " test2 is " << test2 << std::endl;
}

void Boolean::exec2() {
  if ((!test1) && (!test2))
     std::cout << "both test1 && test2 are false" << std::endl;
 else
     std::cout << "test1 is " << test1 << " test2 is " << test2 << std::endl;
}

boolean.h:
class Boolean {
private:
  bool test1;
  bool test2;

public:
  Boolean();
  void exec();
  void exec2();
};

main.cpp:
int main(int argc, char *argv[]) {
Boolean start;
start.exec();
Boolean start2;
start2.exec2();
}

output:

test1 is 1 test2 is 1
both test1 & test2 are false

if I use a default constructor to set test1 and test2 to false at start. the values set in Boolean::exec() get overwritten if I need a new instance of Boolean.

bool test1 = false; declaration is not allowed in a class. without default constructor the bool values are not initialized.

so what's the best solution to declare bool 'false' and keep 'true' if it's set ?


Solution

  • You are declaring two instances of Boolean, these occupy two different memory locations so what you are experiencing is normal behavior

    If you want the two instances to share variables then declare the variables static

    boolean.h:

    class Boolean {
    private:
      static bool test1;
      static bool test2;
    

    an define them in

    boolean.cpp

    Boolean::test1 = false;
    Boolean::test2 = false;
    

    EDIT: note that all instances of Boolean will now share these variables.