Understanding C++ Namespaces

Understanding C++ Namespaces
Play this article

Appropriate for individuals who...

  1. Preparing for C++ Interview.

  2. Passionate C++ developers revising C++ concepts.

Syntax:

namespace <name> {
    // can contain the followings...
    variable, structure, class, function, namespace etc...
}

Why is namespace?

It is used for the following important reasons.

  1. Helps in modularizing the code.

  2. Prevents name clashes.

How to Access the Contents of a Namespace?

  1. global using declarative (opens the entire namespace)

  2. using declarative (opens a specific type)

  3. fully qualified name

Ex: Standard C++ library uses std namespace.

// Opens the entire namespace. cin, cout etc... are available within the scope.
using namespace std; 
cout << "Hello C++\n";

or

// Opens specific type. Here std::cout is opened. But other names like cin is not opened.
using namespace std::cout;
cout << "Hello C++\n";

or

std::cout << "Hello C++\n"; // Fully Qualified Name

Notes:

The namespace within the namespace is known as a nested namespace.

Ex:

#include <iostream>
namespace ex {
    namespace ex2 {
        void fun() { std::cout << "Hello C++\n"; }
    }
}

int main() {
    ex::ex2::fun(); // calling fun() present in nested namespace.
}

Test Code

ASSIGNMENT:
Why Global using Declarative is a bad idea? Write in the comment section.


Want to take your C++ skills to the next level? Visit https://www.cppforme.com for resources, tips, and expert advice to help you improve your coding techniques and become a better developer. And if you need additional help or support, feel free to contact me by visiting my site.