Well having been away (sorry). But I would like to make a summary of were I think we all are.
As is my custom, it will be with examples. Now the discussion is really about scope. In C++ it is possible to have many different variables called the same thing. But the compiler will only allow one variable name per scope. Once you understand the arcane magic called
scoping rules all is easy. (Although true understanding of all scoping rule requires a very very long beard
So to an example. I would like to post complete programs. copy them an run them and see the stangeness on your own computer.
In this case we are going to use the variable name X to mean all the many different X I am going to produce.
#include <iostream>
class A
{
private:
int X;
int Y;
public:
A(int X) : X(17),Y(X+A::X)
{ }
void setY(int X) { Y=X; }
int getX() const { return X; }
int getY() const { return Y; }
};
int X=9;
int
main()
{
int X=8;
A xv(20);
std::cout<<"X in class = "<<xv.getX()<<std::endl;
std::cout<<"Y in class = "<<xv.getY()<<std::endl;
xv.setY(455);
std::cout<<"Y in class= "<<xv.getY()<<std::endl;
std::cout<<"X = "<<X<<std::endl;
std::cout<<"X (globally) = "<<::X<<std::endl;
}
Well I had better have a go an explaining the mess. First off
let us look at class A. It has a class variable X.
I have complicated the thing by calling the constructor with a local method variable X. The rules basically say that the more local a variable is the higher its precedence, i.e. which variable will be called X. All other variables can be obtained but have to be qualified.
so line 10 says: set the variable X in A to 17. Then set variable Y to the local variable X + the class variable X which we just set to 17.
From line 23, Y will be 17+20 == 37.
line 12: setY uses a local variable X. Y is set to that local variable. The class variable X is irrelevent until you change the
setY(int X) to something like
setY(int Z) .
line 17: sets a global variable X.
line 22: sets a local variable X (to the function int main) and as that is more local line 28 use that.
line 29: This shows how to get a global variable when there is a local variable in scope.
Try playing with the values, and the name X to see what happens.
If you understand what goes on here it will make you a MUCH better c++ programmer.