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

Namespace in C++ | Set 1 (Introduction)

Last Updated : 27 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
  • 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
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
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
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
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
Introduction to the C99 Programming Language : Part II
In this article, we are going to discover some more interesting additions to C89 which gave us C99 standard: Variable Argument Lists: C99 brings out a small changes to the preprocessor. Macros can accept a variable number of arguments. These Macros are indicated by ellipsis (...) in their declaration. These Variable Arguments are represented by the
4 min read
Introduction to the C99 Programming Language : Part III
Kindly read Introduction to the C99 Programming Language (Part I) and Introduction to the C99 Programming Language (Part II) before reading this article. Addition of Library Functions: C99 provides some Additional Library functions listed below. Library Function Usage complex.h complex.h supports complex arithmetic fenv.h fenv.h gives access to flo
3 min read
Introduction to Complex Objects and Composition
An object is a basic unit of Object-Oriented Programming and represents the real-life entities. Complex objects are the objects that are built from smaller or a collection of objects. For example, a mobile phone is made up of various objects like a camera, battery, screen, sensors, etc. In this article, we will understand the use and implementation
4 min read
OpenMP | Introduction with Installation Guide
After a long thirst for parallelizing highly regular loops in matrix-oriented numerical programming, OpenMP was introduced by OpenMP Architecture Review Board (ARB) on 1997 . In the subsequent releases, the enthusiastic OpenMP team added many features to it including the task parallelizing, support for accelerators, user-defined reductions and lot
3 min read
Introduction to GUI Programming in C++
In C++, Graphical User Interface (GUI) programming is important in modern application development where users have nice graphics for them to work with. Although C++ is commonly linked with system programming and game writing, it can be an excellent alternative to GUI writing. In this article, we will discuss GUI programming in C++, some popular GUI
5 min read
Introduction to Iterators in C++
An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualized as something similar to a pointer pointing to some location and we can access the content at that particular location using them. Iterators play a critical role in conne
6 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&amp;T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read
Introduction to C++ Programming Language
C++ is a general-purpose programming language that was developed as an enhancement of the C language to include object-oriented paradigm. It is an imperative and a compiled language.  C++ is a high-level, general-purpose programming language designed for system and application programming. It was developed by Bjarne Stroustrup at Bell Labs in 1983
7 min read
Zig - A Brief Introduction
As software systems naturally become more complex, the requirement for new programming languages that are able not only to get good performance but also to be safe and to be on a modern language level increases continuously. This landscape is where Zig resumes its place among venerable low level programming language alternatives , meeting the crite
13 min read
set::begin() and set::end() in C++ STL
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. set::begin() begin() function is used to return an iterator pointing to t
4 min read
Count number of unique Triangles using STL | Set 1 (Using set)
We are given n triangles along with length of their three sides as a,b,c. Now we need to count number of unique triangles out of these n given triangles. Two triangles are different from one another if they have at least one of the sides different.Example: Input: arr[] = {{1, 2, 2}, {4, 5, 6}, {4, 5, 6} Output: 2 Input: arr[] = {{4, 5, 6}, {6, 5, 4
3 min read
Output of C++ Program | Set 10
Predict the output of following C++ programs.Question 1 C/C++ Code #include&lt;iostream&gt; #include&lt;string.h&gt; using namespace std; class String { char *p; int len; public: String(const char *a); }; String::String(const char *a) { int length = strlen(a); p = new char[length +1]; strcpy(p, a); cout &lt;&lt; &quot;Constructor Called &quot; &lt;
2 min read
random header in C++ | Set 1(Generators)
This header introduces random number generation facilities. This library allows to produce random numbers using combinations of generators and distributions. Generators: Objects that generate uniformly distributed numbers.Distributions: Objects that transform sequences of numbers generated by a generator into sequences of numbers that follow a spec
11 min read
C++ set for user define data type
The C++ STL set is a data structure used to store the distinct value in ascending or descending order. By default, we can use it to store system defined data type only(eg. int, float, double, pair etc.). And if we want to store user-defined datatype in a set (eg. structure) then the compiler will show an error message. That is because of the proper
2 min read
Output of C programs | Set 63
Prerequisite : Structure padding, integer promotion and sequence points. Q1. Consider the following code: C/C++ Code #include&lt;stdio.h&gt; struct geeks{ int i; char c; } obj; int main() { printf(&quot;%ld&quot;, sizeof(obj)); } What would be the output of the above code? A. 4 B. 5 C. 8 D. Can't be determined Output: Can't be determined Explanatio
4 min read
set::swap() in C++ STL
Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. set::swap() This function is used to exchange the contents of two sets
2 min read
set::size() in C++ STL
Sets are containers that store unique elements following a specific order. Internally, the elements in a set are always sorted. Sets are typically implemented as binary search trees. The set class provides a member function, set::size() function is used to return the size of the set container or the number of elements in the set container. Syntaxse
1 min read
set::empty() in C++ STL
Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. set::empty() empty() function is used to check if the set container is
2 min read
set::emplace() in C++ STL
Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. set::emplace() This function is used to insert a new element into the s
4 min read
set::clear in C++ STL
Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. set::clear() clear() function is used to remove all the elements of the
2 min read
Using erase_If with Set in C++ STL
The erase_if function in C++20 is used to erase all the elements in the set satisfying the required condition. This condition is referred to as the predicate. The syntax for the erase_if function is erase_if(set, predicate); The first argument of erase function is the set in which elements need to be erased. The second argument is the predicate whi
2 min read
Expressing a number as sum of consecutive | Set 2 (Using odd factors)
Given a number n, find the number of ways to represent this number as a sum of 2 or more consecutive natural numbers. Examples : Input : n = 15 Output : 3 15 can be represented as: 1 + 2 + 3 + 4 + 5 4 + 5 + 6 7 + 8 Input :10 Output :2 10 can only be represented as: 1 + 2 + 3 + 4 We have already discussed one approach in below post. Count ways to ex
6 min read
Article Tags :
Practice Tags :