How to use namespaces in C++?

C++Server Side ProgrammingProgramming

In this article we will see how to use the namespace in C++ code.

Consider a situation, when we have two persons with the same name, Zara, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother’s or father’s name, etc.

Same situation can arise in your C++ applications. For 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. Using namespace, you can define the context in which names are defined. In essence, a namespace defines a scope.

Defining Namespace:

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

namespace namespace_name {
   // code declarations
}

To call the namespace-enabled version of either function or variable, prepend (::) the namespace name as follows –

name::code; // code could be variable or function.

Example Code

#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
raja
Published on 09-Apr-2019 12:24:36
Advertisements