C++ Tutorial – Namespaces and anonymous namespaces

Namespaces are used in the C++ programming language to create a separate region for a group of variables, functions and classes etc. Namespaces are needed because there can be many functions, variables for classes in one program and they can conflict with the existing names of variables, functions and classes. C++ uses namespace to avoid the conflicts.

The concept can be depicted using the following diagram:

namespaces

The following will list the primary reasons due to which a conflict can occur:

  • Between User defined variables/functions/classes and built in Library variables/functions/classes (e.g. sqrt(), abs() etc.)
  • Between the separately included library and built in library
  • Between the variables/functions/classes of the one separately included library and the same of the other separately included library

Creating Namespaces

The C++ language include the keyword “namespace” for creating namespaces.


	namespace 
	{
		members of namespace;
	}

Take a look at an example:


#include<iostream>
using namespace std;

namespace myconstants {
	const double pi = 3.141592;
}

namespace myshapes {
	double area;
	double perimeter;

	void AreaOfCircle(double radius)
	{
		area = myconstants::pi * radius * radius;
	}

	void PerimeterOfCircle(double radius)
	{
		perimeter = 2 * myconstants::pi * radius;
	}
}

int main(int argc, char * argv[])
{
	double r;
	cout << endl << "Enter Radius:";
	cin >> r;
	myshapes::AreaOfCircle(r);
	cout << endl << "Area of the Circle is :" << myshapes::area;
	myshapes::PerimeterOfCircle(r);
	cout << endl << "Perimeter of the Circle is :" << myshapes::perimeter;
}

Namespaces have the following important points:

1) We can have more than one namespace of the same name. This gives the advantage of defining the same namespace in more than one file (although they can be created in the same file as well).

Take a look at an example:


	#include<iostream>
	using namespace std;

	namespace mynamespace
	{
		int x;
	}

	namespace mynamespace
	{
		int y;
	}

	int main(int argc, char * argv[])
	{
		mynamespace::x = mynamespace::y =5;
		cout << mynamespace::x << endl << mynamespace::y;
	}

2)We can have anonymous namespaces (namespace with no name). They are directly usable in the same program and are used for declaring unique identifiers. It also avoids making global static variable.

The “anonymous” namespace you have created will only be accessible within the file you created it in.

Take a look at an example:


	/*This is file1.cpp*/
	#include<iostream>
	using namespace std;

	namespace
	{
		int local;
	}

	void func();

	int main()
	{
		local = 1;
		cout << "Local=" << local << endl;
		func();
		cout << "Local=" << local << endl;
		return 0;
	}


	/* This is file2.cpp */

	namespace
	{
		// Should not collide with other files
		int local;
	}

	void func()
	{
		local = 2;
	}

Note: you will need to include both the files in the same project.

The result of this program should be:

Local = 1

Local = 1

It should not be:

Local = 1

Local = 2

3) C++ has a default namespace named std, which contains all the default library of the C++ included using #include directive.

Using Namespaces

Namespaces are used with the ‘using’ keyword, which makes all the members of the namespace available in the current program and the members can be used directly, without taking reference of the namespace.

Namespaces are also usable by taking their name reference with scope resolution operator. This method allows distinguishing between the members of the same name in two different namespaces.

Take a look at an example:


	#include<iostream>
	using namespace std;

	namespace mynamespace
	{
		int i,j;
	}

	using namespace mynamespace;

	int main(int argc, char *argv[])
	{
		cout << endl << i << ", " << j;
	}

Or without the ‘using’ keyword:


	#include<iostream>
	using namespace std;

	namespace mynamespace
	{
		int i,j;
	}

	int main(int argc, char *argv[])
	{
		std::cout << endl << mynamespace::i << ", " << mynamespace::j;
	}

Namespace alias

It is also possible to declare an alternate name for an existing namespace.

We can use the following format:


	namespace new_name = current_name;

Namespace std

All the files in the C++ standard library declare all of its entities within the std namespace. For that reason we include the ‘using namespace std;’ statement in most programs that is using any entity defined in iostream.

That is all for this tutorial.

This entry was posted in C++ Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There are currently 7 responses to “C++ Tutorial – Namespaces and anonymous namespaces”

Why not let us know what you think by adding your own comment!

  1. kc on September 30th, 2010:

    expalined in simple language !!!!!
    even i never read about namespaces…as i was thinking that it is hard to understand

  2. Surekha Mekin on December 10th, 2010:

    Explained very well. It gives confidence over the topic that can be felt complete.

  3. kk on February 15th, 2012:

    nice

  4. UT on October 12th, 2012:

    good information

  5. karthika on February 18th, 2013:

    excellent

  6. Anand on June 6th, 2013:

    Good one, Before this i was not aware about anonymous namespace. Thanks for that

  7. Anil Kumar on June 14th, 2013:

    I had tried to read it from other books. I either found them boring (much information) or they were difficult to get. This tutorial has shown how simple it is. I don’t know whether really this is a simple topic or you people made it look simple, but it was awesome !
    These tutorials must have been written by experienced peoples !