Don't understand this


This paragraph is from the tutorial Cplusplus Is real confusing....

Notice how in main, the variable x (without any name qualifier) refers to first::x, whereas y refers to second::y, just as specified by the using declarations. The variables first::y and second::x can still be accessed, but require fully qualified names.

using first::x;
using second::y;
These two lines look the same to me, so why is x (without any name qualifier) and y just specified by the using declaration...
Am I missing something???


// using
#include <iostream>
using namespace std;

namespace first
{
int x = 5;
int y = 10;
}

namespace second
{
double x = 3.1416;
double y = 2.7183;
}

int main () {
using first::x;
using second::y;
cout << x << '\n';
cout << y << '\n';
cout << first::y << '\n';
cout << second::x << '\n';
return 0;
}
Last edited on
It shows why using using namespace std; can be a bad practice. Think of it this way, if you take out using namespace std;, you would need to write:
1
2
std::cout << first::y << '\n';
std::cout << second::x << '\n'; 

Since using second::y; is declared in the program, it will use the y value from namespace second unless you specifically tell it to use the one from namespace first.
x and y are defined and initialized in their namespaces, so you can type:
1
2
using first::x; // uses the x variable from namespace first
using second::y; // uses the y variable from namespace second 
Topic archived. No new replies allowed.