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.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

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.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

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.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

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.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

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.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

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.

Learn From The Best Mentors in the Industry!

Automation Testing Masters ProgramExplore Program
Learn From The Best Mentors in the Industry!

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. 

Prepare Yourself to Answer All Questions!

Automation Testing Masters ProgramExplore Program
Prepare Yourself to Answer All Questions!

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

}

Learn 15+ In-Demand Tools and Skills!

Automation Testing Masters ProgramExplore Program
Learn 15+ In-Demand Tools and Skills!

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.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 24 Feb, 2025

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 8 Jan, 2025

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 8 Jan, 2025

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449