The Wayback Machine - https://web.archive.org/web/20240624023100/https://www.geeksforgeeks.org/namespace-in-c/
Open In App

Namespace in C++ | Set 1 (Introduction)

Last Updated : 27 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report
  • Namespace provide the space where we can define or declare identifier i.e. variable,  method, classes.
  • Using namespace, you can define the space or context in which identifiers are defined i.e. variable, method, classes. In essence, a namespace defines a scope.

Advantage of Namespace to avoid name collision.

  • Example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.
  • A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. 
  • The best example of namespace scope is the C++ standard library (std) where all the classes, methods and templates are declared. Hence while writing a C++ program we usually include the directive using namespace std;
     

Defining a Namespace:

  • A namespace definition begins with the keyword namespace followed by the namespace name as follows:
namespace  namespace_name 
{
    // code declarations i.e. variable  (int a;)
    method (void add();)
    classes ( class student{};)
}
  • It is to be noted that, there is no semicolon (;) after the closing brace.
  • To call the namespace-enabled version of either function or variable, prepend the namespace name as follows:
  • namespace_name: :code;  // code could be variable , function or class.

The using directive:

  • You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace. 
  • The namespace is thus implied for the following code:

C++




#include <iostream>
using namespace std;
// first name space
namespace first_space
{
  void func()
  {
     cout << "Inside first_space" << endl;
  }
}
 
// second name space
namespace second_space
{
  void func()
  {
     cout << "Inside second_space" << endl;
  }
}
using namespace first_space;
int main ()
{
   // This calls function from first name space.
  func();
  return 0;
}


Output

Inside first_space
  • Names introduced in a using directive obey normal scope rules. The name is visible from the point of the using directive to the end of the scope in which the directive is found. Entities with the same name defined in an outer scope are hidden.

Nested Namespaces:

  • Namespaces can be nested where you can define one namespace inside another name space as follows:
SYNTAX:
    namespace namespace_name1 
    {
          // code declarations
          namespace namespace_name2 
          {
             // code declarations
          }
    }

You can access members of nested namespace by using resolution operators as follows:
// to access members of namespace_name2
using namespace namespace_name1::namespace_name2;
// to access members of namespace_name1
using namespace namespace_name1;
 

In the above statements if you are using namespace_name1, then it will make elements of namespace_name2 available in the scope as follows:
 

C++




#include <iostream>
using namespace std;
 
// first name space
namespace first_space
{
  void func()
  {
     cout << "Inside first_space" << endl;
  }
  // second name space
  namespace second_space
  {
     void func()
     {
        cout << "Inside second_space" << endl;
     }
  }
}
using namespace first_space::second_space;
int main ()
{
    // This calls function from second name space.
      func();
   
      return 0;
}


Output

Inside second_space

Let us see how namespace scope the entities including variable and functions:

C++




#include <iostream>
using namespace std;
// first name space
namespace first_space
{
  void func()
  {
     cout << "Inside first_space" << endl;
  }
}
// second name space
namespace second_space
{
  void func()
  {
     cout << "Inside second_space" << endl;
  }
}
 
int main ()
{
       // Calls function from first name space.
      first_space :: func();
    // Calls function from second name space.
      second_space :: func();
      return 0;
}


Output

Inside first_space
Inside second_space

Consider the following C++ program: 

CPP




// A program to demonstrate need of namespace
int main()
{
    int value;
    value = 0;
    double value; // Error here
    value = 0.0;
}


Output :

Compiler Error:
'value' has a previous declaration as 'int value'

In each scope, a name can only represent one entity. So, there cannot be two variables with the same name in the same scope. Using namespaces, we can create two variables or member functions having the same name. 

CPP




// Here we can see that more than one variables
// are being used without reporting any error.
// That is because they are declared in the
// different namespaces and scopes.
#include <iostream>
using namespace std;
 
// Variable created inside namespace
namespace first {
int val = 500;
}
 
// Global variable
int val = 100;
 
int main()
{
    // Local variable
    int val = 200;
 
    // These variables can be accessed from
    // outside the namespace using the scope
    // operator ::
    cout << first::val << '\n';
 
    return 0;
}


Output

500

Definition and Creation: Namespaces allow us to group named entities that otherwise would have global scope into narrower scopes, giving them namespace scope. This allows organizing the elements of programs into different logical scopes referred to by names. Namespaces provide the space where we can define or declare identifiers i.e. names of variables, methods, classes, etc.

  • A namespace is a feature added in C++ and is not present in C.
  • A namespace is a declarative region that provides a scope to the identifiers (names of functions, variables or other user-defined data types) inside it.
  • Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope.

A namespace definition begins with the keyword namespace followed by the namespace name as follows:

namespace namespace_name 
{
   int x, y; // code declarations where 
             // x and y are declared in 
             // namespace_name's scope
}
  • Namespace declarations appear only at global scope.
  • Namespace declarations can be nested within another namespace.
  • Namespace declarations don’t have access specifiers (Public or Private).
  • No need to give a semicolon after the closing brace of the definition of namespace.
  • We can split the definition of namespace over several units.

Defining a Namespace:

A namespace definition begins with the keyword namespace followed by the namespace name as follows:
 

C++




namespace  namespace_name{
     // code declarations i.e. variable  (int a;)
     method (void add();)
     classes ( class student{};)
}


It is to be noted that there is no semicolon (;) after the closing brace.
To call the namespace-enabled version of either a function or a variable, prepend the namespace name as follows:

namespace_name: :code;  // code could be a variable, function or class.

C++




// Let us see how namespace scope the entities including variable and functions:
 
#include <iostream>
using namespace std;
 
// first name space
namespace first_space
{
   void func()
   {
      cout << "Inside first_space" << endl;
   }
}
 
// second name space
namespace second_space
{
   void func()
   {
      cout << "Inside second_space" << endl;
   }
}
 
int main ()
{
    // Calls function from first name space.
   first_space::func();
    // Calls function from second name space.
   second_space::func();
   return 0;
}
 
// If we compile and run above code, this would produce the following result:
// Inside first_space
// Inside second_space


Output

Inside first_space
Inside second_space

The using directive:

You can avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace. The namespace is thus implied for the following code:

C++




#include <iostream>
using namespace std;
 
// first name space
namespace first_space
{
   void func()
   {
      cout << "Inside first_space" << endl;
   }
}
 
// second name space
namespace second_space
{
   void func()
   {
      cout << "Inside second_space" << endl;
   }
}
 
using namespace first_space;
 
int main ()
{
    // This calls function from first name space.
   func();
   return 0;
}
 
// If we compile and run above code, this would produce the following result:
// Inside first_space


Output

Inside first_space

Instead of accessing the whole namespace, another option (known as using declaration) is to access a particular item within a namespace. For example, if the only part of the std namespace that you intend to use is cout, you can refer to it as follows:
using std::cout;
Subsequent code can refer to cout without prepending the namespace, but other items in the std namespace will still need to be explicit as follows:

C++




#include <iostream>
using std::cout;
 
int main ()
{
    cout << "std::endl is used with std!" << std::endl;
      return 0;
}


Output

std::endl is used with std!

Names introduced in a using directive obey normal scope rules, i.e., they are visible from the point the using directive occurs to the end of the scope in which the directive is found. Entities with the same name defined in an outer scope are hidden.

C++




// Creating namespaces
#include <iostream>
using namespace std;
namespace ns1 {
int value() { return 5; }
} // namespace ns1
namespace ns2 {
const double x = 100;
double value() { return 2 * x; }
} // namespace ns2
 
int main()
{
    // Access value function within ns1
    cout << ns1::value() << '\n';
 
    // Access value function within ns2
    cout << ns2::value() << '\n';
 
    // Access variable x directly
    cout << ns2::x << '\n';
 
    return 0;
}


Output:

5
200
100

Classes and Namespace: The following is a simple way to create classes in a namespace: 

C++




// A C++ program to demonstrate use of class
// in a namespace
#include<iostream>
using namespace std;
 
namespace ns
{
    // A Class in a namespace
    class geek
    {
    public:
        void display()
        {
            cout<<"ns::geek::display()"<<endl;;
        }
    };
}
 
int main()
{
    // Creating Object of geek Class
    ns::geek obj;
 
    obj.display();
 
    return 0;
}


Output

ns::geek::display()

A class can also be declared inside namespace and defined outside namespace using the following syntax: 

CPP




// A C++ program to demonstrate use of class
// in a namespace
#include <iostream>
using namespace std;
 
namespace ns {
// Only declaring class here
class geek;
} // namespace ns
 
// Defining class outside
class ns::geek {
public:
    void display() { cout << "ns::geek::display()\n"; }
};
 
int main()
{
    // Creating Object of geek Class
    ns::geek obj;
    obj.display();
    return 0;
}


Output

ns::geek::display()

We can define methods as well outside the namespace. The following is an example code: 

C++




// A C++ code to demonstrate that we can define
// methods outside namespace.
#include <iostream>
using namespace std;
 
// Creating a namespace
namespace ns {
void display();
class geek {
public:
    void display();
};
} // namespace ns
 
// Defining methods of namespace
void ns::geek::display()
{
    cout << "ns::geek::display()\n";
}
void ns::display() { cout << "ns::display()\n"; }
 
// Driver code
int main()
{
    ns::geek obj;
    ns::display();
    obj.display();
    return 0;
}


Output:

ns::display()
ns::geek::display():

Nested Namespaces:

Namespaces can be nested, i.e., you can define one namespace inside another namespace as follows:

 

C++




namespace namespace_name1 {
  // code declarations
  namespace namespace_name2 {
     // code declarations
  }
}


You can access the members of a nested namespace by using the resolution operator (::) as follows:
 

C++




// to access members of namespace_name2
using namespace namespace_name1::namespace_name2;
// to access members of namespace:name1
using namespace namespace_name1;


In the above statements, if you are using namespace_name1, then it will make the elements of namespace_name2 available in the scope as follows:
 

C++




#include <iostream>
using namespace std;
 
// first name space
namespace first_space
{
   void func()
   {
      cout << "Inside first_space" << endl;
   }
   // second name space
   namespace second_space
   {
      void func()
      {
         cout << "Inside second_space" << endl;
      }
   }
}
using namespace first_space::second_space;
int main ()
{
  
   // This calls function from second name space.
   func();
    
   return 0;
}
 
// If we compile and run above code, this would produce the following result:
// Inside second_space


Output

Inside second_space

Namespace provides the advantage of avoiding name collision:-

For example, you might be writing some code that has a function called xyz() and there is another library available in your code which also has the same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.
A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables, etc. with the same name available in different libraries. 
The best example of namespace scope is the C++ standard library (std), where all the classes, methods and templates are declared. Hence, while writing a C++ program, we usually include the directive 
using namespace std;
 

namespace in C++ | Set 2 (Extending namespace and Unnamed namespace) Namespace in C++ | Set 3 (Accessing, creating header, nesting and aliasing) Can namespaces be nested in C++? Reference: http://www.cplusplus.com/doc/tutorial/namespaces/



Previous Article
Next Article

Similar Reads

Difference between namespace and class
Classes are data types. They are an expanded concept of structures, they can contain data members, but they can also contain functions as members whereas a namespace is simply an abstract way of grouping items together. A namespace cannot be created as an object; think of it more as a naming convention. It is used as additional information to diffe
2 min read
Why it is important to write "using namespace std" in C++ program?
In this article, we will discuss the use of "using namespace std" in the C++ program. Need of namespace: As the same name can't be given to multiple variables, functions, classes, etc. in the same scope.So to overcome this situation namespace is introduced. Program 1: Below is the C++ program illustrating the use of namespace with the same name of
4 min read
How to Run a C++ Program Without Namespace?
Prerequisite: Namespace in C++ If we want to run a program without using a namespace, we have to the std keyword along with the space resolution operator (::) in every printing line and variable declaration, For example, std::cout&lt;&lt;"geeksforgeeks"; Example: C/C++ Code // C++ Program without the use of using namespace std; #include &lt;iostrea
1 min read
Cons of using the whole namespace in C++
A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organise code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries. Please refer need of namespace in C++ for details.
2 min read
Why "using namespace std" is considered bad practice
The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type. Although the statement saves us from typing std:: whenever we wish to access a class or type defined in the std namespace, it
5 min read
Persistent Trie | Set 1 (Introduction)
Prerequisite: TriePersistency in Data Structure Trie is one handy data structure that often comes into play when performing multiple string lookups. In this post, we will introduce the concept of Persistency in this data structure. Persistency simply means to retain the changes. But obviously, retaining the changes cause extra memory consumption an
15+ min read
Forward List in C++ | Set 1 (Introduction and Important Functions)
Forward list in STL implements singly linked list. Introduced from C++11, forward list are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. It differs from the list by the fact that the forward list keeps track of the location of only the next eleme
9 min read
Understanding "volatile" qualifier in C | Set 1 (Introduction)
In spite of tons of literature on C language, "volatile" keyword is somehow not understood well (even by experienced C programmers). We think that the main reason for this is due to not having real-world use-case of a 'volatile' variable in typical C programs that are written in high level language. Basically, unless you're doing some low level har
5 min read
Introduction to Parallel Programming with OpenMP in C++
Parallel programming is the process of breaking down a large task into smaller sub-tasks that can be executed simultaneously, thus utilizing the available computing resources more efficiently. OpenMP is a widely used API for parallel programming in C++. It allows developers to write parallel code easily and efficiently by adding simple compiler dir
5 min read
Introduction to the C99 Programming Language : Part I
Introduction: C99 is a standardized version of the C programming language that was published in 1999 by the International Organization for Standardization (ISO). It introduced a number of new features and improvements over the previous C89 standard, including support for variable-length arrays, flexible array members, complex numbers, and new keywo
8 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg