Dana Dana - 2 months ago 11
C++ Question

If init lists always be processed to constructor body, but it appears else in my code

So, I've read this:
Will the initialization list always be processed before the constructor code?

and given the following constructor:

A (int x=5):x(x+1)
cout << "In A::A x= " << x << endl;

and the sample of code in the main:

A a1(10);

I don't understand the result:
"In A::A x = 10"
when according to my logic it should be:
"In A::A x = 11"

But instead, x = 11 only after the constructor body invoked. Why is that?


The "problem" with this code is that both the parameter to the constructor and the member variable are named x. That is, x might not refer to the x you expect.

In this case, x refers to the parameter of the constructor - and that has a value of 10. The reason is that when C++ encounters a scope where there are two variables with the same identifier, then the most local scope wins. Here: the x from the parameter value. If you want to use the memver variable, change the code to use this.x instead of just x:

A (int x=5):x(x+1)
    cout << "In A::A x= " << this->x << endl;

Now the value you see should be 11, not 10. this is a pointer to the current object, so this->x is the value of the member variable x of the current object.

Of course, it would be still better to use different names. That way you can avoid such confusion.