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.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

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

  1. Data::Manager mgr;
  2. mgr.task();
  3. Data::Function(mgr)

Keyword "using"

  1. using Data::Manager;
  2. Manager mgr;
  3. mgr.task()

Keyword "using namespace."

  1. using namespace Data;
  2. Manager mgr;
  3. mgr.task();
  4. Function(mgr);

Now, understand the standard namespace.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

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:

Cpp_namespace_Example1

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.

Full Stack Java Developer Course

In Partnership with HIRIST and HackerEarthEXPLORE COURSE
Full Stack Java Developer Course

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:

Cppnamespace_Example2

Example:

Cpp_namespace_Example3

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.

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

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:

Cpp_namespace_Example4

Example:

Cpp_namespace_Example5

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.

Caltech Coding Bootcamp

Become a full stack developer in 6 monthsEnroll Now
Caltech Coding Bootcamp

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:

  1. There can be nested namespaces.
  2. You don't have to use access specifiers.
  3. They don't require semicolons.
  4. 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:

Cpp_namespace_Example6.

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.

FREE Java Certification Training

Learn A-Z of Java like never beforeEnroll Now
FREE Java Certification Training

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:

Cpp_namespace_Example7.

The name of the above file is external.h

Cpp_namespace_Example8.

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:

Cpp_namespace_Example9

If you want to access the members of namespace_name2, then you can write:

Cpp_namespace_Example10

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. 

Free Course: Programming Fundamentals

Learn the Basics of ProgrammingEnroll Now
Free Course: Programming Fundamentals

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.

  1. namespace long-boring-namespace-name { class A{};}
  2. namespace SHORTY = long-boring-namespace-name;
  3. 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. 

Looking to accelerate your career as a skilled Full Stack Web Developer? Leverage Caltech CTME's academic excellence in a unique bootcamp-style Post Graduate Program in Full Stack Web Development. Enroll Now!

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.

About the Author

Kartik MenonKartik Menon

Kartik is an experienced content strategist and an accomplished technology marketing specialist passionate about designing engaging user experiences with integrated marketing and communication solutions.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.