Namespaces and new headers


I told you about the preference of using int main ( ) while writing a C++ program. The programs that we've seen so far are not wrong. But they can't be called as 100% C++ programs either. The reason is simple : we've been making use of header files (such as iostream.h etc...). Making use of these .h files is more similar to C programming. Of course it isn't wrong to use them in C++ but there is a better method. This method makes use of namespaces that we shall see in this section.

Instead of # include <iostream.h> we shall use the following two lines: 

#include <iostream>
using namespace std;

Firstly make note that there is no .h in the include statement. This is one of the new style headers used in C++. They do not use .h I'd like t make another point here (which was the reason that I didn't mention about namespaces earlier). Old C++ compilers may not support namespaces. In case you have such a compiler then you have to stick to the old method of # include. But all the latest C++ compilers will support namespaces.

When C++ was created it used header files. But then changes were made. But it still supports the old header files though they are not recommended. You know that iostream.h is a file. C++ created a new style of its own. In this method we do not specify filenames. Instead it is a method that makes sure that appropriate definitions required by the C++ library have been declared.

The new style headers are not filenames and hence the .h extension is left out. 

When using a new style header you make use of the namespace statement using namespace std; A namespace is a region of declaration. The purpose of namespace is to avoid name collision of identifiers (variables or class names or function names etc...). Elements declared in one namespace are different from those declared in another. For the time being you needn't worry about namespaces. I'll deal with them later. For the time being, always make use of C++ new style headers whenever you write a C++ program.


In the next section we'll take a look at : The final version of your first C++ program

or Go back to Contents page 2.