Namespace

Provides a user defined scope.

 

Useful for objects/functions that are similarly named.

 

For instance, say two objects/functions had the same name, by using the concept of namespaces, we can specify which object/function we are explicitly referring to.

 

The keyword namespace is followed by a user defined identifier for the desired namespace, which then encapsulates the code for that namespace within { curly braces }

 

Syntax:

namespace namespace_identifier {

...bunch

...of

...code

}

 

 

To then call upon a specific object/function within a namespace the scope resolution operator is used, which consists of two colons ::

 

namespace_identifier::myFunc() ; //refers to the myFunc() function in the namespace_identifier namespace

namespace_identifier::myInt ; //refers to the myInt variable in namespace_identifier namespace

 

 

The keyword using directive allows the member of the namespace_identifier to be utilised from that point forward (or until it is redefined), on its own i.e. just using member, like so:

 

using namespace_identifier::member ;

 

Now, member can be used as though it had been declared within the current scope.

 

Alternatively, the keyword using followed by the keyword namespace and the namespace_identifier can be utilised to refer to all members of a specific namespace:

 

using namespace std ;

 

Now all members of the specified namespace can be utilised without further need for the scope resolution operator ::

 

#include <iostream>
using namespace std;

void myFunc(int start, int end, int step){
	for (int i = start ; i <= end ; i += step )	{
		cout << i << '\n';
	}
}

namespace myNameOne {
	int start = 1;
	int end = 5;
	int step = 1;

	void hello(){
		cout << "Now in namespace myNameOne" << endl ;
	}
}

namespace myNameTwo {
	int start = 5;
	int end = 25;
	int step = 5;

	void hello(){
		cout << "Now in namespace myNameTwo" << endl ;
	}
}

int main() {

	namespace XYZ = myNameTwo; //namespace alias

	int a = XYZ::start, b = XYZ::end, c = XYZ::step ;

	myFunc(a,b,c) ;

	myNameOne::hello() ;
	myNameTwo::hello() ;

	using namespace myNameOne ;

	hello() ;

	using myNameOne::start;
	using myNameOne::end;
	using myNameOne::step;

	myFunc(start,end,step) ;

return 0;
}

Compile & Run:

5
10
15
20
25
Now in namespace myNameOne
Now in namespace myNameTwo
Now in namespace myNameOne
1
2
3
4
5

 

 

A namespace alias can also be declared by use of the keyword namespace followed by the preferred alias, which is assigned to the desired existing namespace - as per line 32 above.

Leave a Reply