1

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?

yeah
  • 21
  • 5
  • 1
    Does this answer your question? [What is the default value for C++ class members](https://stackoverflow.com/questions/2614809/what-is-the-default-value-for-c-class-members) – Daniel Langr Oct 30 '19 at 07:17
  • The section on [static storage duration](https://en.cppreference.com/w/cpp/language/storage_duration) explains some of the cases where you can count on zeros. – user4581301 Oct 30 '19 at 07:19
  • 1
    Note that reading an uninitialised variable is Undefined Behaviour and causes the entire program to have no well defined meaning. The compiler is allowed to do *anything* to *any* part of your program when it contains UB. You can no longer reason about it. – Jesper Juhl Oct 30 '19 at 07:28
  • Maybe there is no reason for this situation... – yeah Oct 30 '19 at 07:34

1 Answers1

5

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405