Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for bool in C++

Tags:

c++

boolean

I'm redesigning a class constructor in C++ and need it to catch an unspecified bool. I have used default values for all of the other parameters, but from my understanding bool can only be initialized to true or false. Since both of those cases have meaning in the class, how should I handle checking for change from a default value?

like image 417
voteblake Avatar asked May 05 '09 23:05

voteblake


2 Answers

The reality is that you can't do this. A bool has value, either true or false, and if you haven't initialized it then it is randomly true or false, possibly different at each run of the program or allocation of that class.

If you need to have a type with more options, define an enum.

typedef enum MyBool {
    TRUE,
    FALSE,
    FILENOTFOUND
} MyBool;
like image 161
Steven Canfield Avatar answered Sep 19 '22 12:09

Steven Canfield


Tristate bool is the path to the dark side. Tristate bool leads to anger. Anger leads to hate. Hate leads to suffering.


Prefer not to use a tristate bool.

Instead, use one additional boolean for whether the first boolean is "initialized" (or better, "known") or not.

class Prisoner : public Person
{


  ...

  bool is_veredict_known;
  bool is_guilty;
}

If the veredict is not known yet, you can't tell if the Prisoner is really guilty, but your code can differentiate between the different situations. Of course the Constitution assures that the default value of is_guilty should be false, but, still... :)

By the way, the class invariant should include:

assert(is_veredict_known || !is_guilty);
like image 35
Daniel Daranas Avatar answered Sep 20 '22 12:09

Daniel Daranas