When I write following code it gets compiled and executed properly:
#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 namespace first; //using derective
using second::y;
cout << x << endl;
cout << y << endl;
return 0;
}
But if I write using directives outside main function as follows,
using namespace first; //using derective
using second::y;
int main () {
cout << x << endl;
cout << y << endl;
return 0;
}
It gives this compilation error:
g++ namespace03.cpp -o namespace03
namespace03.cpp: In function ‘int main()’:
namespace03.cpp:20:11: error: reference to ‘y’ is ambiguous
namespace03.cpp:13:10: error: candidates are: double second::y
namespace03.cpp:7:7: error: int first::y
make: *** [namespace03] Error 1
Can anybody explain why using directive behaves differently when it is used inside main and outside main?
The using-declaration is just that, a declaration. The using second::y; inside of main is similar to declaring a variable y in that scope which hides any other ys in global namespace scope. When you use using second::y; in global scope, you have not hidden any names, since both ys are in the same scope.
Imagine your first example is like the following (please see the comments below for an explanation):
namespace first
{
int x = 5;
int y = 10;
}
int main () {
using namespace first; // This makes first::y visible hereafter
int y = 20; // This hides first::y (similar to using second::y)
cout << x << endl;
cout << y << endl; // Prints 20
}
However, the second example is like:
namespace first
{
int x = 5;
int y = 10;
}
using namespace first; // This makes first::y visible in global scope
int y = 20; // This is global ::y
int main () {
cout << x << endl;
cout << y << endl; // Error! Do you mean ::y or first::y?
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With