I have a class named Person which has a name, 4
variables a, b, c, d and a value t
which adds a
, b
, c
, d
up.
Here is the code that describes my problem:
#include <iostream>
using namespace std;
class person {
public:
string name;
int a;
int b;
int c;
int d;
int t = a + b + c + d;
};
int main() {
{
person p;
cin >> p.name >> p.a >> p.b >> p.c >> p.d;
cout << p.t << '\n'; // garbage
}
{
person p;
string s;
int A, B, C, D;
cin >> s >> A >> B >> C >> D;
p = {s, A, B, C, D};
cout << p.t << '\n'; // prints the sum
}
return 0;
}
In the first block, suppose I receive "Andy", 1, 2, 3, 4 from the user, when printing t
, it prints a garbage value. In the second block it prints t
= 10
which I expected, the behavior of the first block is unexpected, I don't know why this happens.