question on c++ object construction and scope

Viewed 57

this is a little bit difficult to put into words, here is the snippet,

int main() {
    int i = 5;
    {
        int i(i);
        i = i+5;
//        int i = i;
//        i = i + 5;

        cout << "inner scope" << endl;
        cout << i << endl;
    }
    cout << "outer scope" << endl;
    cout << i << endl;
}

this give the correct output

inner scope
10
outer scope
5

But if I do this,

int main() {
    int i = 5;
    {
      //int i(i);
      //i = i+5;
        int i = i;
        i = i + 5;

        cout << "inner scope" << endl;
        cout << i << endl;
    }
    cout << "outer scope" << endl;
    cout << i << endl;
}

This throws an runtime exception, and gives wrong output,

inner scope
-858993455
outer scope
5

I feel this seems to be jsomething to do with the difference in the sequence of calling of copy constructor and assignment constructor, but I am not entirely sure, please enlighten me.

1 Answers

When you shadow a variable you remove all trace of it within that scope, so:

int i = i;

This declares i to equal its (uninitialized) self. This variable is completely independent from the parent scope's i. This is effectively undefined behaviour.

Curiously the int i(i) approach uses the parent scope's i to initialize, though that's rather peculiar that it works out. It might not be defined behaviour though.

You should be using a different variable name if you need to relate these two somehow. You can shadow if there's no inter-dependency.

In other words:

int j = i;
Related