Why do we need both using namespace
and include
directives in C++ programs?
For example,
#include <iostream>
using namespace std;
int main() {
cout << "Hello world";
}
Why is it not enough to just have #include <iostream>
or just have using namespace std
and get rid of the other?
(I am thinking of an analogy with Java, where import java.net.*
will import everything from java.net
, you don't need to do anything else.)
In C++
the concepts are separate. This is by design and useful.
You can include things that without namespaces would be ambiguous.
With namespaces you can refer to two different classes that have the same name. Of course in that case you would not use the using
directive or if you did you would have to specify the namespace of the other stuff in the namespace you wanted.
Note also that you don't NEED the using - you can just used std::cout or whatever you need to access. You preface the items with the namespace.