Java/J2EE and SOA (349 Blogs) Become a Certified Professional

Everything You Need to Know about Namespace in C++

Published on Aug 09,2019 7K Views


Namespace in C++ is used to organize code into logical groups and to prevent name collisions that can occur especially when your codebase includes multiple libraries. In this article the following Pointers will be covered:

 

The need for Namespace

Consider a situation, we are writing some code that has a function called abc() and there is another predefined library available which is also having same function abc(). Now at the time of compilation, the compiler has no clue which version of abc() function we are referring to within our code.

Namespace in c++

To overcome this difficulty namespace is designed and is used as additional information to differentiate similar functions, variables, classes, etc. with the same name available in different libraries. Using namespace, we can define the context in which names are defined. In essence, a namespace defines a scope.

All C++ standard library types and functions are declared in the std namespace or namespaces nested inside std thus it is widely used in most of the programs.

 

Defining a Namespace

To define namespace we start with the keyword namespace followed by the namespace name as follows:

namespace namespace_name 
{
   int a, b; // code declarations where 
             // a and b are declared in 
             // namespace_name's scope
}

 

 

Points to remember while defining a Namespace

  • Namespace declarations appear only at global scope.
  • Namespace declarations don’t have access specifiers.
  • Namespace declarations can be nested within another namespace.
  • No need to give semicolon after the closing brace of the definition of the namespace.
  • Namespace definition can be split over several units.
#include <iostream>
using namespace std;

namespace first_function {
   void func() {
      cout << "Inside first_function" << endl;
   }
}
namespace second_function {
   void func() {
      cout << "Inside second_function" << endl;
   }
}

int main () {
   // Calls function from first name space.
   first_function::func();
   
   // Calls function from second name space.
   second_function::func(); 

   return 0;
}

Output:

Output-Namespace-in-C++

In the above example to define the func() function two different times, we use the namespace concept. We define the first function under namespace first_function and second function under namespace second_function. To call these functions we use scope resolution operator in the following manner – first_function::func(); and second_function::func();.

 

Using Namespace in C++

There are three ways to use a namespace in the program,

  1. The using directive
  2. The using-declaration
  3. Scope Resolution Operator (::)

 

The using directive

We can avoid prepending of namespaces with the using namespace directive. using keyword allows us to import an entire namespace into your program with a global scope. It can be used to import a namespace into another namespace or any program according to our requirement.

Consider a header file Namespace_first.h:

namespace First
{
    int a;
    class First_class
    {
        int i;
    };
}

Including the above namespace header file in Namespace_second.h file: include “Namespace_first.h”;

namespace Second
{
    using namespace First;
    First_class obj;
    int y;
}

We import the namespace_First into namespace_Second, hence class First_class will now be available in the namespace_Second. Hence we can write the following program in a separate file, let’s say new_file.cpp.

#include "Namespace_second.h";

void test()
{
    using namespace Second;
    // creating object of class First_class
    First_class obj2;
}

Hence, the using directive makes it a lot easier to use a namespace in C++, wherever you want.

 

The using-declaration

In the using-declaration, we import one specific name at a time which is available only inside the current scope and it is called with the help of scope resolution. NOTE: The name imported with using-declaration can override the name imported with using directive. We can see this in the example below.

Let us consider a header file New_File.h:

namespace First
{
    void A()
    {
        cout << "A of First namespacen";
    }
  
 }

namespace Second
{
    void A()
    {
        cout << "A of Second namespacen";
    }
}

 

Now let’s create a new program file with name New_file_2.cpp with below code:

#include "New_file.h";

void B()
{
    using namespace First;  // using directive

    using Second::A; // using declaration

    First::A(); // class A() of First namespace

    A();    // calls A() of Second namespace    
}

using-namespace-in-c++

 

Scope resolution operator (::)

We can explicitly specify any name declared in a namespace using the namespace’s name and the scope resolution “::” operator with the identifier.

namespace New_space
{
    class X
    {
        static int i;
        public:
        void func();
    };
    
    // class name declaration
    class Y;    
    
}

// Initializing static class variable
int New_space::X::i=23;      

class New_space::Y
{
    int a;
    public:
    int getdata()
    {
        cout << a;
    }
    // Constructor declaration
    Y();   
}

// Constructor definition explicitly
New_space::Y::Y()   
{
    a=0;
}

 

Discontiguous Namespace in C++

As we know a namespace in C++ can be defined in several parts thus it is made up of the sum of its separately defined parts. So, if one part of the namespace requires a name defined in another file, that name must still be declared in its scope. Writing the following namespace in the following manner either defines a new namespace or adds new elements to an existing one:

namespace namespace_name {
   // code body
}

 

Nested Namespace in C++

Namespaces can be nested easily and we can define one namespace inside another namespace as follows:

namespace namespace_name1 {
   // code body of namespace_name1
   namespace namespace_name2 {
      // code body nested namamespace_name2
   }
}

 

With this, we come to an end of the Namespace in C++ article. I hope you got an idea of what exactly is a namespace in C++ and what are the different ways of defining it. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 7th December,2024

7th December

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Everything You Need to Know about Namespace in C++

edureka.co