Open In App

Namespace in C++

Last Updated : 23 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Name conflicts in C++ happen when different parts of a program use the same name for variables, functions, or classes, causing confusion for the compiler. To avoid this, C++ introduce namespace.

Namespace is a feature that provides a way to group related identifiers such as variables, functions, and classes under a single name. It provides the space where we can define or declare identifier i.e. variable, method, classes. In essence, a namespace defines a scope.

Namespace Definition

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

C++
namespace name {
    // type1 mamber1
    // type2 mamber2
    // type3 mamber3
    .    .     .
    .    .     .
}

It is to be noted that, there is no semicolon (;) after the closing brace.

For example,

C++
// Define a namespace called 'first_space'
namespace first_space {
    void func() {
        cout << "Inside first_space" << endl;
    }
}

Accessing Members

We can access the members of namespace using scope resolution operator(::).

Syntax:

C++
namespace_name::member_name;

Example:

C++
//Driver Code Starts{
#include <iostream>

// Define a namespace called 'first_space'
namespace first_space {
    void func() {
        std::cout << "Inside first_space" << std::endl;
    }
}

int main() {
    
    // Access member of namespace
//Driver Code Ends }

    first_space::func();   
    return 0;

//Driver Code Starts{
}

//Driver Code Ends }

Output
Inside first_space

Namespace with using Directive

We can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace.

C++
#include <iostream>

namespace first_space {
    void func() {
        std::cout << "Inside first_space"
            << std::endl;
    }
}

// Using first_space
using namespace first_space;

int main() {
    
    // Call the method of first_space
    func();  
    return 0;
}

Output
Inside first_space

Names introduced in a using directive obey normal scope rules. The name is visible from the point of the using directive to the end of the scope in which the directive is found. Entities with the same name defined in an outer scope are hidden.

Instead of accessing the whole namespace, another option (known as using declaration) is to access a particular item within a namespace. For example, if the only part of the std namespace that you intend to use is cout, you can refer to it as follows:

C++
#include <iostream>

namespace first_space {
    void func() {
        std::cout << "Inside first_space" << std::endl;
    }
}

// Using first_space
using first_space::func;

int main() {
    
    // Call the method of first_space
    func();  
    return 0;
}

Output
Inside first_space

Nested Namespace

We can nest one namespace into another. Such namespaces are called nested namespaces.

Example:

C++
// Outer namespace
namespace outer {
    void fun(){
        cout << "Inside outer namespace" << endl;
    }
    
    // Inner namespace
    namespace inner {
        void func() {
            cout << "Inside inner namespace";
        }
    }
}

Accessing members in nested namespaces require multilevel scope resolution as shown:

C++
//Driver Code Starts{
#include <iostream>
using namespace std;

// Outer namespace
namespace outer {
    void fun(){
        cout << "Inside outer namespace" << endl;
    }
    
    // Inner namespace
    namespace inner {
        void func() {
            cout << "Inside inner namespace";
        }
    }
}

int main() {
    
//Driver Code Ends }

    // Accessing member of inner 
    // namespace
    outer::inner::func();  

//Driver Code Starts{
    return 0;
}

//Driver Code Ends }

Output
Inside inner namespace

In-built Namespaces

C++ already uses some inbuilt namespaces that we are already familiar with. Let’s look at some of the common ones:

std Namespace

In C++, std namespace is the part of standard library, which contains most of the standard functions, objects, and classes like cin, cout, vector, etc. It also avoids conflicts between user-defined and library-defined functions or variables.

C++
#include <iostream>
using namespace std;

int main() {
    int a = 3, b = 7;
    
    // 'cout' and 'endl' are part of the std namespace
    cout << "Sum: " << a + b ;  
    return 0;
}

Output
Sum: 10

Note: ADL (Argument-Dependent Lookup) in C++ is a feature that automatically searches for functions or operators based on the types of the function’s arguments.

Global Namespace

The global namespace is the default namespace where all the functions, variables, and classes that are not explicitly declared inside any namespace. Everything outside of any namespace is considered to belong to the global namespace.

We can access the global namespace using scope resolution operator(::) followed by global namespace name.

Example:

C++
//Driver Code Starts{
#include <bits/stdc++.h>
using namespace std;

int n = 3;

int main() {
    int n = 7;
    
//Driver Code Ends }

    // Accessing global namespace
    cout << ::n << endl;
    cout << n;

//Driver Code Starts{

    return 0;
}
//Driver Code Ends }

Output
3
7

Extending Namespace

In C++, extending a namespace means adding more features (like functions, variables, or classes) to an existing namespace, even if that namespace was defined somewhere else (like in a library or another file).

Example:

C++
//Driver Code Starts{
#include <bits/stdc++.h>
using namespace std;

//Driver Code Ends }

namespace nmsp{
    void func(){
        cout << "You can extend me" << endl;
    }
}

// Extending the same namespace
namespace nmsp{
    void func2(){
        cout << "Adding new feature";
    }
}

int main() {
    nmsp::func();
    nmsp::func2();

//Driver Code Starts{

    return 0;
}
//Driver Code Ends }

Output
You can extend me
Adding new feature

Creating an Alias for Namespace

We can also create an alias of existing namespace using namespace.

C++
namespace namespace_name{
    // Members of namespace
}

// Creating a alias of namespace_name
namespace nn = namespace_name;

Inline Namespace

An inline namespace is a type of namespace where its members are accessible directly without using the namespace name.

Example:

C++
//Driver Code Starts{
#include <iostream>
using namespace std;

//Driver Code Ends }

inline namespace inline_space {
    void display() {
        cout << "Inside inline namespace";
    }
}

int main() {
    
    // Direct access due to inline namespace
    display();  

//Driver Code Starts{
    return 0;
}

//Driver Code Ends }

Output
Inside inline namespace

Anonymous Namespace

A namespace does not have a name called an anonymous namespace. It ensures that the entities in the unnamed namespace are limited to that file.

Example:

C++
//Driver Code Starts{
#include <iostream>
using namespace std;

//Driver Code Ends }

// Anonymous namespace
namespace {
    int value = 10;
}

int main() {
    
    // Accessing anonymous namespace variable
    cout << value;  

//Driver Code Starts{
    return 0;
}

//Driver Code Ends }

Output
10

Namespace vs Class

Namespaces and classes may look similar, but they are completely different. The differences between namespaces and classes are shown below:

NamespaceClass
It is used to organize code and prevent name collisions in large projects.Used to define and create objects that encapsulate data and behavior.
Does not encapsulate data or behavior; it only provides scope.Encapsulates both data members and methods into objects.
Does not have access modifiers (public, private, protected).Has access modifiers (public, private, protected) to control the visibility of members.
Cannot be inherited.Can be inherited to create subclasses.
A namespace is not instantiated; it is used to group entities.A class is instantiated to create objects.
Does not directly consume memory; it only provides scope for identifiers.Consumes memory as objects are created from a class.
Used to organize code and avoid name conflicts, especially in large projects.Used to create objects and model real-world entities with attributes and behaviors.
No constructors or destructors.Has constructors and destructors to initialize and destroy objects.


Next Article
Article Tags :
Practice Tags :

Similar Reads