NAMESPACES

I have mentioned namespaces several times, so it’s time you got a better idea of what they are about. They are not used in the libraries supporting MFC, but the C++ standard library uses namespaces extensively.

You know already that all the names used in the standard library are defined in a namespace with the name std. This means that all the names used in the standard library have an additional qualifying name, std; for example, cout is really std::cout. You have already seen how you can add a using declaration to import a name from the std namespace into your source file. For example:

using std::cout;

This allows you to use the name cout in your source file and have it interpreted as std::cout.

Namespaces provide a way to separate the names used in one part of a program from those used in another. This is invaluable with large projects involving several teams of programmers working on different parts of the program. Each team can have its own namespace name, and worries about two teams accidentally using the same name for different functions disappear.

Look at this line of code:

using namespace std;

This statement is a using directive and is different from a using declaration. The effect of this is to import all the names from the std namespace into the source file so you can refer to anything that is defined in this namespace without qualifying the name in your program. Thus, you can write the name cout instead of std::cout and endl instead of std::endl. This sounds ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.