C++ Namespaces1 min read

Suppose there is a function called abc() in your code and you are also using some library that has the function with the same name as abc(). Now while executing these functions, the compiler will not know which one to execute among two abs() functions. In such cases namespace comes into action.

A namespace is used to overcome the above situation in a program. It is used as additional information for functions, classes, etc. It allows us to organize the elements of the program into a logical group so that the collision of multiple libraries can be prevented.

Defining a Namespace

The keyword “namespace” is used to define the namespace class and to call prepend (::) the namespace such as:

namespace namespace_name
{
void func() {
// body of function
}
}

//to call, inside main
namespace_name::func();

It could be variable or function in a program.


Example of namespace in C++

Output:

Hello space_ONE
Hello space_Two


C++ program for a namespace with the use of directive.

Here we use using keyword and avoid prepending a namespace.

Output:

Hello space_ONE


MORE

Keith Number Program in C

In this tutorial, we will write a Keith number in C. It is one of the most asked questions in an interview. Before that, you …
Read More

Keith Number Program in C++

In this tutorial, we will write a Keith number in C++. It is one of the most asked questions in an interview. Before that, you …
Read More

Singly linked list Program C++

In this tutorial, we will write a C++ program to implement singly linked list. In this program, we will create a separate function for each …
Read More

Fascinating Number Program in C

In this tutorial, we will write a C program to check whether the given number is a Fascinating number or not. You may go through …
Read More

Peterson Number in C

In this tutorial, we will learn about the Peterson number and check if the number is Peterson or not in C. What is Peterson Number? …
Read More

Peterson Number in C++

In this tutorial, we will learn about the Peterson number and write a C++ program to check if the given number is a Peterson number …
Read More