In Oriley's C++ in a Nutshell, a namespace is defined as:
Quote:
| A namespace is a named scope. |
Code:
namespace1::fraction namespace2::fraction namespace3::fraction
You can place a namespace into one file, but we will be using a header file and an extra .ccp file for this namespace. So first we will construct the header file. open a new header file in your compiler and type in the
following.
Code:
#include <iostream>
using namespace std;
namespace newnspace
{
void describe(void);
int addNums(int, int);
}For the second file we will use, open a new .cpp file and name it newnspace.cpp. I find it helpful to name my files according to their contents but I do not believe it is neccessary. In this file we will define the functions that we previously set up. So here is what we type into the new file.
Code:
#include "newnspace.h"
void newnspace::display(void)
{
cout << "This is a namespace" << endl;
cout << "They are like classes except you do not" << endl;
cout << "Need to declare an object to access their members" << endl;
return;
}
int newspace::addNums(int num1, int num2)
{
return num1 + num2;
}The last file we have to write is main.cpp. The code for this is simple.
Code:
#include <iostream>
#include "newnspace.h"
using namespace std;
using namespace newnspace;
int main(void)
{
display();
cout << addNums(1, 3) << endl;
system("pause");
}Now many beggining programers will not be creating packages or using multiple classes with the same name in a program. So you may be asking "Why would this be practical?" Well let's say that you have a bunch of functions. Functions for manipulating strings, for searching arrays, for sorting arrays, all kinds of reusable functions. Now lets say you want to put them in a class. Well first you have to declare an object of the class type and then use that object to access the classes members. This process is tedious and inconvenient not to mention somewhat of a misuse of classes. If you were to put these functions into an external namespace however, you could just use the namespace and call the functions whenever you want! In longer programs, this will lead to less errors and less code.
In conclusion, namespaces are a powerful part of the C++ language for both beginning and experienced programmers.
The code for this tutorial was written and compiled in Dev-C++ so you may need to alter it to make it work in other compilers. I hope that you enjoyed my second tutorial. If you have any revisions, or would like to contribute to the information, please post a reply.
discuss this topic to forum
