I used to know that uninitialized member variables are initialized with a garbage value.
But, If there is a pointer variable uninitialized in a class, all of the uninitialized member variables are initialized with zero.
I think the pointer variable is just pointing an instance in heap memory.
Why are other variables changed?
I don't know what the difference is between these initializations.
Below is the code I tried for step by step.
#include <iostream>
using namespace std;
class Test {
private:
int val1;
int val2;
public:
void PrintValue() {
cout << "val1: " << val1 << endl;
cout << "val2: " << val1 << endl;
}
};
int main() {
Test a;
a.PrintValue();
}
then, the result is
val1: -858993460
val2: -858993460
In this code, I added 'int* ptr = new int' like below.
#include <iostream>
using namespace std;
class Test {
private:
int val1;
int val2;
int* ptr = new int;
public:
void PrintValue() {
cout << "val1: " << val1 << endl;
cout << "val2: " << val1 << endl;
}
};
int main() {
Test a;
a.PrintValue();
}
The result is like this.
val1: 0
val2: 0
Why does this happen?
I'm using VS community 2019 and build tools v142.