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

匿名 (未验证) 提交于 2019-12-03 01:12:01

问题:

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();    } } 

回答1:

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. } 


回答2:

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.



回答3:

C / C++ don't initialize variables for you at all. The memory location which is now in use by bar had a value in it which is interpreted as "true". This will not always be the case. You must initialize it in your constructor.



回答4:

This program has undefined behavior. Intrinsic types do not have constructors. You could do bool bar = bool(); but it's better to define the actual value in your foo class.



回答5:

Since you're using the value of bar in the ctor, I assume you're trying to set it before the object is created? I think you meant to make it a static class variable instead of an instance variable.



回答6:

Try this:

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


回答7:

You can initialize any variable when you declare it.

bool bar = 0; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!