Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

namespace
c++

What are namespaces in C++?

Educative Answers Team

Namespaces allow entities like classes, objects, and functions to be grouped together under one name. This way, the global scope is divided into “narrower” scopes that are identifiable by name.

Namespaces are created in C++ as follows:

namespace myNamespace {
   int a;
}

To call the namespace-enabled version of a function or a variable, prepend :: to the function or variable’s name:

myNamespace :: a;

The functionality offered by namespaces is very useful in cases where redefinition of functions, variables, or classes, is a risk. The examples below highlight this functionality:

Using the :: syntax

#include <iostream>
using namespace std;

namespace first
{
  string str = "I am from the first namespace.";
}

namespace second
{
  string str = "I am from the second namespace";
}

int main ()
{
  cout << first::str << endl;
  cout << second::str << endl;
  return 0;
}
The string variables 'str' are differentiable because they occur in different namespaces.

You may have noticed that using namespace std;is used in several C++ codes; this is because all the files in the C++ standard library declare all of their entities within the std namespace. Therefore, by using the std namespace, we are able to use all of the iostream functions without attaching std:: before them. Theusing keyword is just an alternative to using ::.

Using the using keyword

#include <iostream>
using namespace std;
namespace first
{
  string str = "I am from the first namespace.";
}

namespace second
{
  string str = "I am from the second namespace";
}

int main ()
{
  /* 
    'using namespace' has validity only in the block in 
    which it is stated or, 
    in the entire code (if it is declared globally).
    This is why both namespaces made below are also
    made in seperate blocks using {}.
  */
  {
    using namespace first;
    cout << str << endl;
  }
  {
    using namespace second;
    cout << str << endl;
  }
}

RELATED TAGS

namespace
c++
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring