codescracker


c++

C++ Namespaces



« Previous Tutorial Next Tutorial »


Namespace in C++, is designed to overcome that type of difficulty where there is similar functions, variables, or classes, etc available in a C++ program, then namespace is used as additional information to differentiate those similar functions, classes, variables etc.

C++ Namespace Definition

Here is the general form to define a namespace in C++:

namespace namespace_name
{
   // declaration codes
}

Here is the general form to call a namespace in C++:

name::code;

Here, code represents the variable/function

C++ Namespace Example

Here are some example program using namespace in C++

/* C++ Namespace - Example Program */

#include<iostream.h>
#include<conio.h>
using namespace std;
namespace first_namespace
{
	void fun1()
	{
		cout<<"Inside first_namespace\n";
	}
}
namespace second_namespace
{
	void fun2()
	{
		cout<<"Inside second_namespace\n";
	}
}
void main()
{
	clrscr();
	first_namespace::fun1();
	second_namespace::fun2();
	getch();
}

Here is the output of the above C++ program:

Inside first_space
Inside second_space

Here is another example program, also demonstrating namespace in C++

/* C++ Namespace - Example Program */

#include<iostream.h>
#include<conio.h>
using namespace std;
namespace first_namespace
{
	void fun()
	{
		cout<<"Inside first_namespace\n";
	}
}
namespace second_namespace
{
	void fun()
	{
		cout<<"Inside second_namespace\n";
	}
}
using namespace first_namespace;
void main()
{
	clrscr();
	fun();		// calls function from first namespace
	getch();
}

Here is the sample output of this C++ program:

Inside first_namespace

Below is one more example program, illustrating namespace in C++

/* C++ Namespace - Example Program */

#include<iostream.h>
#include<conio.h>
using std::cout;
void main()
{
	clrscr();
	cout<<"std::endl is used with std"<<std::endl;
	getch();
}

Following is the sample output of the above C++ program:

std::endl is used with std

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test