CH 14namespaces
CH 14namespaces
Introduction
• Real applications or programs consist of many source or library files.
These files can be used and maintained by more than one developer or
programmer.
• As it uses different library files in a program there might be the cases
where there are same function or variable names being used. Because
of this there arises the name conflict problem.
• Namespace mechanism in C++ overcomes the problem of name
clashes in the global scope. The namespace mechanism allows an
application to be partitioned into different packages or enclosure.
Each enclosure can define and operate within its own scope.
• For eg we are using Math library and some educational library in our
program. Math library has abs() function to calculate absolute value
and education library has abs() for counting absent students. Here the
name confliction problem occurs.
• Namespaces are used to solve such name conflict problems.
• - The namespaces declaration identifies and assigned a unique
name to a user declared namespace. Namespaces allow
distinguishing names declared in different files
}
// Defining class member function outside the namespace
Namespace MyNamespace
{
class brother
{
string name;
public:
brother(string brothername);
};
}
MyNamespace::Brother::brother(string brothername)
{
MyNamespace::brother::Name = brothername;
}
Int main()
{
MyNamespace::brother Lara(“kevin);
cout<<Lara; }
Unnamed namespace
• Use the keyword namespace without identifier before the closing
brace. This can be superior alternative to the use of the global static
variable declaration.
• - The syntax:
• namespace { namespace_body }
int main()
{
cout<< “Enter number”;
cin>> Mynumber;
cout<<Mynumber;
};
Nested Namespaces
• We can define a namespace within another namespace.
• To access the element deep inside the nested namespace
we have to use the qualification using the syntax :
outerNamespace :: innerNamespace::elementName
Namespace Aliases
• When we have to give the long qualifications to access the namespace
element, we can use aliases to shorten them to access.
Namespace OuterNamespace
{
namespace InnerNamespace
{
class brother
{
string name;
public:
brother (stirng brothername)
{ name = brothername; }
};
}
}
• int main()
{
namespace NS = OuterNamespace::InnerNamespace;
NS::brother Lara(“kevin”);
Cout<< Lara;
}
Koenig Lookup
• Koenig lookup enables the compiler to find out namespace for
an element even if it is not mentioned with either using
directive or declarative or even fully qualified.
• The formal name of the algorithm is Augment dependent
lookup;