Namespaces are regions in a program logically separated from the rest. They are necessary if you want more than one function with the same name. You can declare two different namespaces for these functions and call them by referencing their corresponding namespace.Ā
It is similar to referencing the second names when two people have the same first name. So namespace tells the compiler which of the two identically named functions to use.
What Is the C++ Namespace?
Namespace in C++ is the declarative part where the scope of identifiers like functions, the name of types, classes, variables, etc., are declared. The code generally has multiple libraries, and the namespace helps in avoiding the ambiguity that may occur when two identifiers have the same name.
For example, suppose you have two functions named calculate(), and both are performing different tasks. One calculate() function is doing the multiplication, and another is doing the addition. So in this case, to avoid ambiguity, you will declare both the functions in two different namespaces. These namespaces will differentiate both the functions and also provide information regarding both the functions.
Definition
You can define a namespace as follows:
namespace namespace_name
{
Ā Ā Ā Ā Ā Ā int a, b;Ā
}
Important points to consider while declaring a namespace:
- You can only define them in a global scope.
- It is only present in C++ and not in C.
- To access a class inside a namespace, you can use namespacename::classname.Ā
C++ Namespace Example
namespace Data
{
class Manager
{
public:
void task() {}
};
void Function(Manager) {}
}
C++ Namespace Example: By Using Keyword
You can access the class inside the above namespace in three ways:
Qualified Name
- Data::Manager mgr;
- mgr.task();
- Data::Function(mgr)
Keyword "using"
- using Data::Manager;
- Manager mgr;
- mgr.task()
Keyword "using namespace."
- using namespace Data;
- Manager mgr;
- mgr.task();
- Function(mgr);
Now, understand the standard namespace.
Using Directives
You use the "using" directive to import the entire namespace into a program or another namespace. This directive eliminates the need to use the "namespace-name" every time. So it is better to use the "using" if you need several functions or classes from the namespace. Otherwise, if you only need to use it once or twice, "namespace-name" would be a better choice. Further, if the namespace contains a variable with the same names as the local one, the namespace variable is hidden.Ā
The Global Namespace
Say you did not declare the identifier in an explicit namespace. In that case, the identifier will be in the global namespace. However, it is better not to declare identifiers in the global namespace. You can use ::SomeFunction to differentiate an identifier in the global namespace from the one in any other namespace.Ā
Standard Namespace
The std is a short form of standard, the std namespace contains the built-in classes and declared functions.
You can find all the standard types and functions in the C++ "std" namespace. There are also several namespaces inside "std."
Example:
Here std is used in front of cin and cout along with scope resolution operator, which indicates that the object cin and cout are defined inside the namespace whose name is std.
The std is the standard library, and both cin and cout are defined inside this scope.
Now, learn how to define C++ Namespace.
How Do You Define Namespace in C++?
To define a namespace, first, the namespace keyword is written in the beginning and then the name of the namespace, and inside the brackets, there are declarations.
Syntax:
Example:
Here, the name of the namespace is the column, and the variable named data is declared as its member.
Now, understand how to access C++ namespace members.
How to Access Namespace Members?
As you have understood how to define your own namespace, you will now learn how to access the contents of this namespace.
To access the namespace members, you can use the name of the namespace and the member name, along with the scope resolution operator.
Syntax:
Example:
Here data variable whose value is 20 is declared in the namespace and another variable data having value 140.57 is declared in the main function. To print both the variables we have to put the namespace name in front of the data variable having value 20 i.e column::data, otherwise both data variables will print 140.57.
So to print the value of a namespace member, we have to write a namespace with its scope, which will avoid the name clash.
Declaring Namespaces and Namespace MembersĀ
You usually declare namespaces in a header file. And then, you use that namespace in a program after including the header file. Consider the following header file "data.h"
//data.h
namespace Server
{
void cho();
int cha();
}
Now let's use the header file in myfile.cpp. You must use a fully qualified name for function implementation. It doesn't matter that you have used the "using" directive.Ā
#include "data.h"
using namespace Server;
void Server::cho() //fully-qualified name
{
cha(); //fully-qualified name not required
}
int Server::cha(){return 0;}
You can declare namespaces in multiple blocks and different files. Then, during the preprocessing, the compiler will joint all the parts. The std namespace is such an example. It is in every header file.Ā
You can define the members outside the namespace where you declare them. For example
namespace A{
void m();
}
void A::m() { //code}
However, the declaration must be before the definition.Ā
Creation
While creating a namespace, remember that:
- There can be nested namespaces.
- You don't have to use access specifiers.
- They don't require semicolons.
- You can have one namespace in different blocks and even other files.
Using Namespace in C++
If we want to use the namespace or access the members of the namespace, we will write the namespace name and scope resolution operator then the name of the namespace member.
Namespace_name::namespace_memeber. But if we want to include a section or block of code into the namespace then we can use the using directive.
The using directive is positioned at the top of the program and it allows us to access all the namespace members.
Syntax:
Most commonly, the above syntax is used to write the using namespace std, a predefined standard library that gives access to various functions like cin, cout, etc.
External Namespace
External namespacing is done when we have multiple namespaces in the program. To keep all the namespace members in a separate file, you create the namespace file with all the members and include the file in the program.
Once it is declared at the top of the program, then you can use the members anywhere in the program.
Example:
The name of the above file is external.h
You can easily access the namespaces after including the file in the header.
Now, move on and understand Nested namespaces in C++
Nested Namespace
As you know about nested loops, similarly, there are Nested namespaces as well, i.e., a namespace defined inside another namespace.
As mentioned before, you can create a nested namespace. You have to use a qualified name to access the nested namespace from the parent. However, nested namespaces can access the parent namespace without a fully qualified name.Ā
Syntax:
If you want to access the members of namespace_name2, then you can write:
So, this is how nested namespaces are declared and accessed from outside.
Following is an example of a nested namespace.
namespace Flight
namespace Flight
{
void fly();
namespace details
{
int speed;
void thrust() { return fly(); }
}
int fuel(){...};
int air(){int i}{return details::speed; }
}
In the above example, the namespace details are nested under the parent Flight.Ā
Inline Namespace
Inline namespaces are not like ordinary nested namespaces. Instead, the compiler treats the members of the inline namespace as it would treat the parent namespace. So if B is an inline namespace of the namespace A, then B's identifiers will be A's members.Ā
That means you can have functions with overloads in a parent and a nested inline function.Ā
Following is an example of an inline namespace.Ā
//Header.h
#include<string>
namespace Fake
{
namespace old
{
std::string Function() { return std::string("we meet again"); }
Ā }
inline namespace new
{
std::string Function() { return std::string("nice to meet you");}
}
}
Let us use the above header in a program.
# include "header.h"
# include <string>
# include <iostream>
int main()
{
using namespace Fake;
using namespace std;
string s = Function();
std::cout << s << std::endl;
return 0;
}
Namespace Aliases
The namespace names can be lengthy; however, you can make aliases if you think writing will be tedious. They will also make your code more readable. You can do that in the following way.
- namespace long-boring-namespace-name { class A{};}
- namespace SHORTY = long-boring-namespace-name;
- void B (SHORTY::A a){}
Anonymous or Unnamed Namespaces
Another property of the namespaces is that they don't need names. So, for example, the following is a valid namespace.
namespace
{
int MyFunction(){}
}
These types of namespaces are anonymous or unnamed namespaces. This way, you can make a code invisible to other files, but you don't create a named namespace. So only the code inside the file will see the namespace and its identifiers. Other files will not.Ā
Scope Resolution Operator
Scope resolution operator "::" enables us to qualify hidden names and makes them usable to other code. You can use it to access identifiers inside namespaces and classes. For example:
#include < iostream>
using namespace std;
class X
{
public:
static int count;
};
int X::count = 5; //assigning value
int main ()
{
cout << X::count << endl; //printing value
}
Discontiguous Namespace in C++
You read above that the Namespaces in C++ can be in different blocks and files. Such types of Namespaces having its parts in more than one location are Discontiguous Namespaces.Ā
Advantage
The primary advantage of namespaces is that they resolve any naming conflict. For example, sometimes, you may need more than one function with the same name. And namespaces provide a way to declare such functions without making the compiler ambiguous.Ā
Disadvantage
The primary disadvantage of namespaces is that there can be conflicts when using multiple libraries. This is because they may have namespaces with the same names.Ā
Conclusion
Hope this article was able to provide you with everything you needed to know about Namespace in C++. If you are looking to enhance your skills further, then do check out Simplilearnās Post Graduate Program in Full Stack Web Development. This course is designed in collaboration with Caltech CTME and can help you hone your skills and make you job-ready in just 6 months.Ā
If you have any questions or doubts, feel free to post them in the comments section below. Our team will get back with the solutions at the earliest.