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;
}
Also
false
So what‘s the cause that influence the data member value of class? Shouldn't all of this test outputs with true
?
Aucun commentaire:
Enregistrer un commentaire