Menu
C++ Tutorials

C++

Namespaces



Tutorials > C++ > Namespaces

View Full Source

What is a Namespace?

A namespace is created to allow you to group certain functions and variables by some name.

A namespace is created as follows :

    namespace name { functions and variables; }

Why are they useful?

If you want to have 2 variables with the same name, the compiler will not know which one to use. If each variable is declared within a different namespace, you are able to differentiate between the two. Namespaces allow you to get rid of unnecessary amiguity. std is an example of a namespace.

Contents of main.cpp :


#include <iostream>
#include <stdlib.h>

using namespace std;

First we create a player namespace. This namespace consists of 2 variables and one function.

namespace player
{
	int health = 100;
	char *name;

	void attack()
	{
		cout << "Player attacks" << endl;
	}
}

Next, we create an enemy namespace. The health variable is given a different value and the attack function prints out a different message.

namespace enemy
{
	int health = 30;

	void attack()
	{
		cout << "Enemy attacks" << endl;
	}
}

int main()
{

To access members within a namespace, the scope (::) operator is used.

	player::attack();
	enemy::attack();

	cout << player::health << endl;

You can also use the using namespace set of keywords followed by the name of the namespace to use that namespace for the current scope. We have seen this a lot when dealing with the std namespace.

In the code below, you can see how using the using namespace player allows you to use the variables without showing the namespace followed by the scope operator.

	// CODE BLOCK
	{
		using namespace player;
		health = 50;
		attack();
	}

Now that the above code is out of scope, we have to go back to using the player namespace in the normal way.

	cout << player::health << endl;

You can also choose to only use a specific function or variable by having :

using namespace_name::func_or_var_name

	using enemy::health;
	cout << health << endl;

	system("pause");

	return 0;
}

Well done. You should now have an idea of how namespaces work. You may be wondering why it is not just better to use everything at once. Separating work and only activating namespaces at certain times allows ambiguity to be avoided and allows you to make sure you are using the correct information. If someone else writes a library and places all data within a namespace, it at least allows you to create variables and functions with the same names.

Please let me know of any comments you may have : Contact Me

Source Files : Visual Studio Dev-C++ Unix / Linux

< Tutorial 43 - String-Number Conversions Tutorial 45 - Function Templates >

Back to Top


All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005

Read the Disclaimer

Links