Reputation: 21
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
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