yeah
yeah

Reputation: 21

What will cause the data members in class initialized to zeros?

Default constructor shouldn't zero out any data member. But in some situation, it seems not to be like this.

The code example is brief.

#include <iostream>

using namespace std;

class Foo {
public:
  int val;
  Foo() = default;
};

int main() {
  Foo bar;
  if (bar.val != 0) {
    cout << "true" << endl;
  } else {
    cout << "false" << endl;
  }
  return 0;
}

As excepted, above program outputs:

true

However, if a print statement for bar's data member added, the var member will be initialized to zero:

...
int main() {
  Foo bar;
  cout << bar.val << endl;
  ...
}

The outputs will be:

0
false

Similarly, if adding virtual function and destructor to the class Foo:

#include <iostream>

using namespace std;

class Foo {
public:
  virtual void Print() {}
  ~Foo() {}
  int val;
  Foo() = default;
};

int main() {
  Foo bar;
  if (bar.val != 0) {
    cout << "true" << endl;
  } else {
    cout << "false" << endl;
  }
  return 0;
}

or just init bar object:

class Foo {
public:
  int val;
  Foo() = default;
};

int main() {
  Foo bar = Foo();
  ...
}

outputs with:

false

So what‘s the cause that influence the data member value of class? Shouldn't all of this test outputs with true?

Upvotes: 1

Views: 92

Answers (1)

songyuanyao
songyuanyao

Reputation: 172934

As default initialization in this case:

otherwise, nothing is done: the objects with automatic storage duration (and their subobjects) are initialized to indeterminate values.

Note that indeterminate value includes 0, which is a valid result too. BTW reading these indeterminate values leads to UB.

Upvotes: 5

Related Questions