Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a C++ bool var true by default?

bool "bar" is by default true, but it should be false, it can not be initiliazied in the constructor. is there a way to init it as false without making it static?

Simplified version of the code:

foo.h

class Foo{
 public:
     void Foo();
private:
     bool bar;
}

foo.c

Foo::Foo()
{  
   if(bar)
   {
     doSomethink();
   }
}
like image 950
Christoferw Avatar asked Jan 11 '10 18:01

Christoferw


People also ask

Is a boolean variable true by default?

Remarks. Use the Boolean Data Type (Visual Basic) to contain two-state values such as true/false, yes/no, or on/off. The default value of Boolean is False . Boolean values are not stored as numbers, and the stored values are not intended to be equivalent to numbers.

What is the default bool value in C?

The default value of the bool type is false .

Is bool true by default C++?

A boolean data type in C++ is defined using the keyword bool . Usually, 1 ( true ) and 2 ( false ) are assigned to boolean variables as their default numerical values.

Is bool by default false C++?

Only global variables are assigned 0 (false) by default. Any local variables are given a non-zero garbage value, which would evaluate to true in a boolean variable. Show activity on this post. Yes.


2 Answers

In fact, by default it's not initialized at all. The value you see is simply some trash values in the memory that have been used for allocation.

If you want to set a default value, you'll have to ask for it in the constructor :

class Foo{
 public:
     Foo() : bar() {} // default bool value == false 
     // OR to be clear:
     Foo() : bar( false ) {} 

     void foo();
private:
     bool bar;
}

UPDATE C++11:

If you can use a C++11 compiler, you can now default construct instead (most of the time):

class Foo{
 public:
     // The constructor will be generated automatically, except if you need to write it yourself.
     void foo();
private:
     bool bar = false; // Always false by default at construction, except if you change it manually in a constructor's initializer list.
}
like image 83
Klaim Avatar answered Sep 19 '22 01:09

Klaim


Klaim's answer is spot on. To "solve" your problem you could use a constructor initialization list. I strongly suggest you read that page as it may clear up some similar queries you may have in future.

like image 44
Nick Bolton Avatar answered Sep 22 '22 01:09

Nick Bolton