Basic namespace query

May 12, 2013 at 9:33pm
I'm starting up C++ after being familiar with C, Java and Python. I'm unsure about some concepts behind including headers. I'm currently using the Eclipse C++ IDE, only because of installation issues with Visual Studio on my current desktop.

The code below uses extern ostream cout as part of the output stream. If iostream has the source for cout etc, why do we have to use the std namespace as well? Is this because its implementations use the standard library?

Thanks

1
2
3
4
5
6
7
#include <iostream>
using namespace std;

int main(){
        cout << "output" << endl;
	return 0;
}
May 12, 2013 at 10:16pm
The code uses std::cout, which is a global variable of type std::ostream declared in the header <iostream> and std::endl, which is a non-member template function declared in the header <ostream> (which is included by <iostream>)

It could be equivalently written as

1
2
3
4
5
#include <iostream>
int main()
{
    std::cout << "output" << std::endl; // or just "output\n"
}


When you write "cout" without any qualifications, the compiler examines the current namespace (and finds nothing in your case) and, among other things, the namespaces pulled in with the using-declarations (the std namespace in your case, where it finds std::cout)
May 12, 2013 at 10:34pm
Ok thanks, this is a lot clearer to me now.
Topic archived. No new replies allowed.