Namespaces
What's in a Namespace?
You may be familiar with global variables and you have probably been taught that global variables are evil. It is true that they should be avoided if possible, but global variables are sometimes the right tool for the job. The reason that as a student you are taught to avoid global variables is that they introduce a potentially nasty problem into your programs called "name collision". Name collision occurs when two or more variables that share the same scope are declared with the same name. This problem can be particularly nasty if you are working on a large project and you use some third party libraries that happen to use some of the same global variable names. In the best case the name collision occurs in your code and you can just rename some of your globals, but in the worst case it is the third party libraries that are fighting and you don't have access to the source so there is nothing you can do! One way to help avoid this is by using namespaces. Namespaces are simply a way to define a new "scope". It's a bit like a library where you can store all of your globals and have easy access to them. One namespace you should already be familiar with is "std". In order to use classes such as cout, cin, and endl you have to first include iostream, which is where the "std" namespace "lives". Now you have to somehow tell the compiler you want to use the std namespace. There are a few methods to accomplish this.
The long way looks like this:
std::cout << "This way takes a lot of keystrokes!" << std::endl;
You have to type std:: to get access to anything in the std namespace so you will end up with a lot more keystrokes in a big project. Another way is to selectively include only parts of the namespace:
using std::cout;
using std::cin;
using std::endl;
This gives you access to cout, cin, and endl without having to type std::, but ONLY for those three members of std.
For our purposes, the best way is just to use the entire namespace like this:
using namespace std;
Now you have access to ALL members of the std namespace by just typing in the member's name.
You can define your own namespaces, but that is a tutorial all on its own! After you have seen classes we may come back to namespaces since they are both similar.