I am new to namespaces and was trying this from C++ Primer
#include<iostream> namespace Jill { double bucket; double fetch; struct Hill{ }; } double fetch; int main() { using namespace Jill; Hill Thrill; double water = bucket; //double fetch; //<<<<<<<<<<<<// std::cin>> fetch; std::cin>> ::fetch; std::cin>> Jill::fetch; std::cout<<"fetch is "<<fetch; std::cout<<"::fetch is "<< ::fetch; std::cout<<"Jill::fetch is "<< Jill::fetch; } int foom() { Jill::Hill top; Jill::Hill crest; } When the line marked //<<<<<<<<<<<<// is not commented I get expected results. i.e. the local variable hides the global and Jill::fetch. But when I comment it out, there are 2 fetch left . global fetch and Jill::fetch. And the compiler gives the error
namespaceTrial1.cpp:17:13: error: reference to ‘fetch’ is ambiguous namespaceTrial1.cpp:9:8: error: candidates are: double fetch namespaceTrial1.cpp:5:9: error: double Jill::fetch namespaceTrial1.cpp:20:26: error: reference to ‘fetch’ is ambiguous namespaceTrial1.cpp:9:8: error: candidates are: double fetch namespaceTrial1.cpp:5:9: error: double Jill::fetch My question is why does the compiler get confused this lead to ambiguity? Why does it not assume fetch as just Jill::fetch , since I have added using namespace Jill at the start of main()
If I use declarative using Jill::fetch; at the start of main, the issue gets solved. because using Jill::fetch makes it as if it has been declared at that location. So, its like there is a local fetch variable. [Am i correct?] Why does using declaration behave as if the variable was declared at that location and using directive doesnt?