Search code examples
c++classgarbage

Why the first block of code results in garbage value, while the second block adds up the values of class members?


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.


Solution

  • In the first case your default initializer for t is used. Though when t is initialized via a + b + c + d, the members a,b,c and d havent been initialized yet. You only assign values after creating the object:

    // create object with members not initialized
    person p;   
    // write values
    cin >> p.name >> p.a >> p.b >> p.c >> p.d;
    // garbage
    cout << p.t << '\n'; // garbage
    

    The middle line is irrelevant for what you see for t, because t is initialized only once, before the constructor runs. Setting the other members later has no effect on the value of t.

    In the second case you use aggregate initialization. As you supply values for all members but the last, t will again be initialized using the default initializer. In this case, at the time t is initialized all other members already have been initialized (members are initialized in the order they appear in the class definition). Hence you see the correct value.