I was going through the Namespace topics and found that when we compile the below code the compiler complaints
[Error] reference to 'cout' is ambiguous
#include <iostream>
void cout()
{
std::cout << "In cout function\n";
}
int main()
{
using namespace std;
cout << "Hello, world!\n";
return 0;
}
But if we replace using namespace std with using std::cout, the program runs successfully and produces the expected output. How is this possible?
#include <iostream>
int cout()
{
std::cout << "In cout function\n";
}
int main()
{
using std::cout; //REPLACED
cout << "Hello, world!\n";
return 0;
}
As far as I am aware the only difference between using std::cout and using namespace std
is,
using std::cout -> imports only cout from std namespace, while
using namespace std -> imports all the variables from std.
In both of the cases cout() function and std::cout variable are visible within main function. So how is using std::cout resolving the issue while using namespace std is not able to?