What is a Namespace?
Since we are talking about the scope-resolution operator, it's a good time to mention another use of it.
We talked about how a class is like a collection of variables and functions. Well, it's not the only way to collect variables and functions together!
A namespace is also a collection of functions and variables, and that is its only purpose: to be a named collection.
The main purpose of namespaces is to avoid name collisions! For example, imagine that Carol's code has a function cowTime
and Kamala's code also has a function cowTime
. Your program needs to use both of those functions, but now you have a double-declaration error!
The solution is a namespace. A namespace wraps around a bunch of variables and functions so they don't interfere with anything else. If Carol and Kamala both defined their own name spaces (say carol
and kamala
), then we could distinguish between the two functions by saying carol::cowTime
and kamala::cowTime
.
Namespace std
(What Does std::
Mean?)
All of the standard library code is in the namespace std
.
If your code defined a variable cout
, but your file also included iostream
, there would not be a name collision because there would actually be two different variables, one named std::cout
(from iostream
) and one named cout
(from your own code).
So, to print something out, you might need to write
std::cout << x << std::endl;
That does seems clunky to me.
Agreed, it can be a real pain to always type
std::
(although you can get used to it).There are things we can do to help that, though!
Using using namespace std;
You may have noticed that some of our example files have the line
using namespace std;
at the top.Yeah! I've been wondering about that!
The line using namespace std
basically says to unwrap everything in the std
namespace so we can refer to it directly. That allows us to print something out with just
cout << x << endl;
without the extra std::
s.
But dumping all the std
names into our program's namespace isn't a total win. We now run the risk of name collisions—for example, we can no longer have our own variable named cout
.
For the code we're writing in CS 70, the trade-off is often worthwhile but there are still some “ettiquette” rules we need to follow:
- It's fine to put
using namespace std;
in a source (.cpp
) file, if you want. - It's not okay to put
using namespace std;
in a header (.hpp
) file that other people will#include
into their code.
What's the deal with header files?
Other people will include our header file in their code. It's uncool for us to dump the
std
namespace names into their code environment. It should be their choice, not ours.
Okay, we've learned a lot about classes and namespaces. Let's head up to the parent page and check our progress and maybe take a break.
(When logged in, completion status appears here.)