In C++, namespaces serve the purpose of structuring numerous classes for better management within an application. They provide a means to group interconnected identifiers like variables, functions, classes, and methods to prevent conflicts in naming. In C++, accessing a class within a namespace requires the syntax namespacename::classname. To simplify this, the "using" namespace keyword can be employed to avoid repeated usage of complete names.
Syntax
It has the following syntax:
namespace namespace_name {
// declarations
}
A namespace can be declared by utilizing the namespace keyword succeeded by the specified namespace identifier.
Accessing Members of Namespace
When accessing the members of a namespace in C++, it is necessary to employ the scope resolution operator.
Syntax
It has the following syntax:
Namespace_name::Member_name
C++ Namespace Example
Let's explore a basic illustration of the namespace, encompassing variables and functions.
Example
#include <iostream>
using namespace std; //using standard namespace
namespace First {
void sayHello() {
cout<<"Hello First Namespace"<<endl;
}
}
namespace Second {
void sayHello() {
cout<<"Hello Second Namespace"<<endl;
}
}
int main() //Main Function
{
First::sayHello();
Second::sayHello(); //Accessing Members using scope resolution operator
return 0;
}
Output:
Hello First Namespace
Hello Second Namespace
Explanation
In this instance, we establish two namespaces, namely First and Second, wherein each namespace accommodates a sayHello function. Within the main function, we access both functions by employing the scope resolution operator (First::sayHello and Second::sayHello). This method ensures distinct and unequivocal function invocations from each respective namespace.
Namespace with using keyword
The using directive allows us to import a complete namespace from another program file into our current program. This eliminates the need to repeatedly specify the namespace every time we want to access variables within the program, making use of the using keyword instead.
Syntax
It has the following syntax:
using namespace namespace_name;
C++ Namespace example using the Using Directive
Let's consider a scenario to demonstrate the concept of namespace in C++ by utilizing the "using" directive.
Example
#include <iostream>
using namespace std; //using standard namespace
namespace First{
void sayHello(){
cout << "Hello First Namespace" << endl;
}
}
namespace Second{
void sayHello(){
cout << "Hello Second Namespace" << endl;
}
}
using namespace First;
int main () { //main function
sayHello();
return 0;
}
Output:
Hello First Namespace
Explanation
In this illustration, we declare two namespaces, First and Second, each containing a sayHello function. When "using namespace First;" is employed, the compiler invokes First::sayHello within the main function. Subsequently, accessing Second::sayHello requires full qualification or an extra using directive.
In-built Namespaces
There are various predefined namespaces in C++. Some key functions within the C++ standard namespace include:
Global Namespace
The global namespace serves as the primary namespace in C++. Any symbol defined outside of a named namespace is part of the global namespace. In the absence of a specified namespace, entities like variables, functions, and classes are automatically placed within the global namespace.
In C++, the :: (scope resolution operator) can be used without a preceding namespace name to explicitly reference the global namespace within another namespace.
Syntax
It has the following syntax:
::identifier // Access global variable, function, or class
C++ Global Namespace Example
Let's consider an example to demonstrate the global namespace in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
int value = 10; // Global namespace variable
namespace cpptutorial {
int value = 20;
void show() {
cout << "Local namespace value: " << value << endl;
cout << "Global namespace value: " << ::value << endl;
}
}
int main() { //main function
cpptutorial::show();
return 0;
}
Output:
Local namespace value: 20
Global namespace value: 10
Explanation
In this instance, we demonstrate how namespaces and scope resolution are applied. Subsequently, a global variable is initialized to 10, while within the cpptutorial namespace, a separate variable is set to 20. Following this, the show function is employed to showcase both variables: the one from the cpptutorial namespace and the global variable accessed using the scope resolution operator (::).
Using the std Namespace
In C++, the std (standard) namespace encompasses all the classes and functions found in the Standard Library, such as cout, cin, string, vector, and more. This feature enables us to avoid clashes in names with user-defined identifiers.
If we intend to utilize the components within the std namespace, we can follow these steps.
1) Use the scope resolution operator (std::)
Example: std::cout << "Hello";
2) Use the using directive (using namespace std;)
It permits direct access sans std::, yet it may result in name clashes.
3) Use using declarations (using std::cout;)
It selectively imports particular items from the namespace.
C++ std Namespace Example
Let's consider an example to demonstrate the std namespace in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() { //main function
cout << "Hello from std namespace" << endl;
return 0;
}
Output:
Hello from std namespace
Explanation
In this instance, we showcase a basic message utilizing the standard namespace. With the addition of using namespace std;, it allows us to directly utilize cout and endl without the need to prefix them with std::.
Nested Namespaces
In C++, nested namespaces enable the creation of a namespace within another namespace. This feature proves beneficial for structuring code hierarchically, especially in larger projects. By preventing naming clashes and enhancing code clarity, it contributes to better code organization.
Syntax
It has the following syntax:
namespace Outer::Inner {
// body of the code
}
C++ Nested Namespace Example
Let's consider an example to demonstrate the concept of nested namespaces in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
namespace Company { //namespace outer
namespace Project { //namespace inner
void showDetails() {
cout << "Welcome to the Company Project" << endl;
}
}
}
namespace Tech::Development {
void greet() {
cout << "Welcome to the Development Department" << endl;
}
}
int main() { //Main function
// Accessing functions from nested namespaces
Company::Project::showDetails();
Tech::Development::greet();
return 0;
}
Output:
Welcome to the Company Project
Welcome to the AI Department
Explanation
In this instance, we showcase nested namespaces employing both conventional and simplified syntax introduced in C++17. Subsequently, the function Company::Project::showDetails is implemented utilizing the conventional nested namespace approach, whereas Tech::Development::greet leverages the concise C++17 syntax. The main function accesses both functions through scope resolution.
C++ Namespace MCQs
1) Which of the following options is utilized to signify the namespace?
- Scope Resolution Operator
- Conditional Operator
- Bitwise Operator
- Ternary Operator
2) What will be the output of the following code?
#include <iostream>
using namespace std; //using standard namespace
namespace first
{
int var = 8;
}
namespace second
{
double var = 4.1754;
}
int main () //Main Function
{
int a;
a = first::var + second::var;
cout << a;
return 0;
}
- Compilation Error
3) Which of the following directive is utilized for namespace in C++?
- including namespace
- accessing namespace
- with namespace
- using namespace
4) Which of the following statements is correct about namespace in C++?
- A namespace is mainly utilized to group classes, objects, and functions.
- A namespace is utilized to separate the class and objects.
- A namespace is mainly utilized to mark the start and end of the program.
- A namespace is mainly utilized to mark the start of the program.
a) A namespace is primarily used to group together classes, objects, and functions.
5) What will be the output of the following code?
#include <iostream>
using namespace std; //using standard namespace
namespace Box1
{
int x = 20;
}
namespace Box2
{
int y = 18;
}
int main () //Main function
{
int x = 10;
Box1::x;
Box2::y;
cout << x;
return 0;
}