DEV Community

Aastha Gupta
Aastha Gupta

Posted on • Edited on

Quick Introduction to namespaces in C++

As someone who writes C++ code often, I see (and use) the keyword namespace frequently and I think it is worth knowing what this keyword is all about.

A namespace is a region that provides a scope to the identifiers (the names of functions, variables, etc) inside it. namespaces are used to organize code into logical groups. All identifiers in the namespace scope are visible to one another.

The identifiers in the namespace can be accessed by bringing those said identifiers into the current scope by using or utilizing fully qualified names.

using namespace std;
// the namespace std is now in scope
string my_string;

std::string my_string
// fully qualified name
Enter fullscreen mode Exit fullscreen mode

Declaring namespace and namespace members

A namespace declaration is generally done in a header file as following:

// my_namespace_declaration.h

namespace my_own_namepsace
{
    void func_one();
    int func_two();
}
Enter fullscreen mode Exit fullscreen mode

The members of this namespace can then be brought into scope of any other file by fully qualified names or the using directive. (If you want to know more about using, checkout this article by me)

// other_file.cpp

#include"my_own_namepsace.h"
using namespace my_own_namepsace;

my_own_namepsace::func_one();
// fully qualified names are to be used
// even when bringing the namespace in 
// scope with using directive
Enter fullscreen mode Exit fullscreen mode

Code in a header file that uses identifiers from other namespaces should always use the fully qualified namespace name to avoid ambiguity. This isocpp core guideline puts more light.

Nested namespaces

namespaces can be nested. A nested namespace has unqualified access to its parent's members however the parent members do not have unqualified access to the nested namespace (unless it is declared as inline).

The std namespace

All C++ standard library types and functions are declared in the std namespace or the various namespaces that are nested inside std which makes it one of the most common namespaces to be encountered.

This article is a short introduction and if you want to know more about namespaces, I encourage you to head over here.

Thanks for giving this article a read and I'll see you in the next one 😄

PS: This is an article in my series Quick Introduction to a concept in C++. You can find all the articles in this series here.

Top comments (0)