Understanding C++ Namespaces and its Methods

Understanding C++ Namespaces and its Methods

5 mins read256 Views Comment
Updated on Oct 9, 2023 18:39 IST

In this article, you will understand the C++ namespaces. We have covered various topics such as its creation, namespace declaration guideline, methods of using namespace, advantages and disadvantages.

2023_02_C-Namespaces.jpg

Namespaces is a new feature in C++ as it was not present in C. C++ namespaces provide a way to differentiate variables, functions, and classes that have the same name by creating a scope for each set of identifiers. A complete name, which includes the namespace, is necessary to gain access to identifiers within a namespace. Namespaces play a crucial role in C++ as they prevent naming conflicts in the code. As long as different namespaces define the same identifier, they can have the same name.

Must Read: What is C++?

This tutorial will discuss how to create namespaces in C++, the rules for creating a namespace in C++, and their advantages and disadvantages. We will be covering the following sections:

Must Check: C++ Online Courses and Certifications

Introduction to C++ Namespace

Imagine a classroom with two students having the same name. To tell them apart, we need to use their full names, including their last names. The same can occur in C++. For example, if we create a function named “sqrt(),” but it already exists in the cmath library of C++, the compiler won’t know which one to use and will result in an error. To prevent such confusion, we use namespaces in C++.

Namespaces serve as a solution for avoiding naming conflicts in a program. They provide a way to distinguish between variables, functions, or classes with the same name by adding an extra layer of information.

Check out: Array of Strings in C++

Creating a Namespace in C++

Defining a namespace in C++ is similar to defining a class. The following syntax can be make in use to namespace in C++:

 
namespace MyNamespace {
// Function, class, and variable declarations.
}
Copy code

We can declare variables, functions, classes, and nested namespaces within the namespace.

Declaring all members of a namespace at once is not a requirement. Instead, we can define nampespace in multiple sections, each with its own set of declarations. This type of namespace, known as a “discontiguous namespace,” is formed by combining the scopes of each section.

Namespace Declaration Guidelines

To use namespaces in C++, it is important to follow these guidelines:

  1. It is necessary to declare a namespace either globally or within another namespace.

2. An alias can provide an alternative name for the namespace.

3. Unnamed namespaces are possible, and the members of such namespaces are treated as if they belong to the parent namespace.

4. It is necessary to redefine or overwrite namespace definitions when they span multiple files.

5. Namespace declarations do not have public or private access specifiers.

You can also explore: Erasing Elements from a Vector in C++

Methods of Using Namespaces in C++

Using Scope Resolution Operator

We can use the scope resolution operator (::) with the namespace name to access any variables, functions, or classes declared within that namespace.

Example:

 
#include <iostream>
using namespace std;
namespace NS1 {
void hello() {
cout << "Hi! This is namespace NS1." << endl;
}
}
namespace NS2 {
void hello() {
cout << "Hi! This is namespace NS2." << endl;
}
int var = 100;
int func() {
return var * 3;
}
}
int main() {
/*
* Run the hello() function present in NS1.
* Used scope resolution operator to call this function.
*/
//
NS1::hello();
// Run the greet() function present in NS2.
NS2::hello();
return 0;
}
Copy code

Output:

The above code demonstrates the use of namespaces to resolve naming conflicts. We can define two namespaces, NS1 and NS2, each with a hello() function. In the main program, these functions are called using the scope resolution operator (::) with the respective namespace name, avoiding any naming conflicts.

You can also explore: Understanding Copy Constructor in C++

Using Directive

The using directive allows us to bring an entire namespace from another program file into our program file. Therefore, the imported namespace will have a global scope and can also be imported into another namespace or program. 

The syntax for the using directive is as follows:

using namespace namespace_name;

Example:

Suppose we have a header file called “namespace_example1.h” that contains the namespace as given below:

 
// namespace_example.h
namespace Office {
int capacity = 500;
class Employees {
int employee_total = 350;
};
}
Copy code

Now, let’s include this file in a C++ program named “main. cpp,” as shown below:

 
// main.cpp
// Including the header file.
#include "namespace_example.h"
void office() {
// using directive.
using namespace Office;
/* Now, all variables, functions, and classes are in the namespace.
Office can be directly used here. */
// Creating an object named e1 of the class Employees.
Employees e1;
}
Copy code

The class “Employees” was defined in the file “namespace_example.h”, but it could be utilized in the “main.cpp” file due to the presence of a using directive.

Note: Experts advice to avoid using directives as they can lead to importing unneeded variables, functions, or classes and result in ambiguity. Code should use the scope resolution operator or “using-declaration”.

Using Declarations

The using declaration is different from the using directive in that it only imports one namespace member at a time using the scope resolution operator. And, the imported member is only available in the current scope. 

The syntax for using-declaration is:

using namespace_name::member_name;

Example:

 
// namespace_example.h
namespace NS1 {
void displaytext() {
cout << "This function is inside namespace NS1" << endl;
}
void greet() {
cout << "Greetings by namespace NS1" << endl;
}
}
namespace NS2 {
void displaytext() {
cout << "This function is inside namespace NS2" << endl;
}
void greet() {
cout << "Greetings by namespace NS2" << endl;
}
}
Copy code

So, we will now import this to our “main.cpp” file:

 
// main.cpp
#include <iostream>
using namespace std;
#include "namespace_example.h";
using namespace NS1; // Using directive.
using NS2::displaytext; // Using declaration.
int main()
{
// Calling displaytext() function.
displaytext();
// Calling the greet() function.
greet();
return 0;
}
Copy code

In the program mentioned, the using directive was used to bring all the members of namespace NS1 into the program. Additionally, in contrast, the using-declaration was used to import the print_text function from namespace NS2 specifically. This means that when the displaytext() function was called in line 14, the function from namespace NS2 was executed. Still, when the greet() function was called in line 17, the greet() function from namespace NS1 was executed as it wasn’t imported from namespace NS2.

Working with Pairs in C++
Working with Pairs in C++
In this article, we will learn what are pairs in C++, and how to initialize pairs in C++. Some common C++pairs STL functions. Later in the article, we will also...read more
C++ Input Output | Basics of cin and cout in C++
C++ Input Output | Basics of cin and cout in C++
Do you know how a computer gets information from you or gives you information? Just like C has scanf and printf, in C++ we use ‘cin’ and ‘cout’. ‘Cin’ takes...read more

Advantages of Namespaces in C++

  • They provide a way to group related entities and organize the code.
  • It is possible to reduce the chances of name collisions between identifiers in different parts of a program with Namespaces.
  • They make it easier to manage and maintain large projects.
  • They allow us to use identifiers with the same name in different parts of a program without causing conflict.

Disdvantages of Namespaces in C++

  • Namespaces can make the code difficult to read and understand.
  • Overuse of namespaces can lead to complex and hard-to-follow code.
  • Namespaces can add an extra layer of abstraction that makes it harder to debug the code.
  • Using directives or using declarations can lead to unexpected results, making it difficult to trace the origin of identifiers

Endnotes 

This article helped you grasp the concept of C++ Namespaces. Namespaces provide a mechanism for organizing and grouping similar entities. Moreover, they also allow for easy management of different functions, variables, and classes.

Explore our C++ articles to learn more about the language and consolidate your knowledge of the fundamentals. Especially, head over to brush up on the basics by reading about the difference between C and C++.

Contributed By: Prerna Singh

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio