Namespaces

Consider the following code snippet

int main()
    {
        int var;
        var = 5;
        float var = 7.0;        //Error
    }

There is an error in the statement float var = 7.0;
because it declares a variable using a name which has already being used in this scope.
This is not allowed.
As our programs increase in size, the number of identifiers also increases and sooner or later we feel that we don’t have any meaningful identifier left to name our variable or function that has not already been used.
Here’s what namespaces are used for.
Namespace simply is an area of code which guarantees that every identifier inside it is unique.
So we want to use two variables of same name in one scope, we can put them in different namespaces.
Note: By default, all global variables and global function definitions are in global namespace.

To define a namespace use the keyword namespace and follow this syntax

namespace namespace-name
    {
        ………
        some definitions
        ………
    } 

Example

    namespace n1
    {
        int x = 5;
        void foo()
        {
            cout << x;
        }
    }

We can put variables, function definitions and even classes inside a namespace.

To access the variable ‘x’ of namespace n1, we use scope resolution operator (::) like n1::x;
And similarly to call foo() function of namespace n1, we use n1::foo();
We can also define classes within a namespace.
Let’s see an example,

namespace n2
    {
        class A
        {
            int a;
            public:
            int getA()
            {
                return a;
            }
        };
    }

Now there is a class ‘A’ inside namespace ‘n2’.
We can create an object of this class like n2 :: A obj;
And now use this object to call member functions of this class obj.getA();

Note: std is a namespace that we are using from very beginning without knowing much about namespaces.
It is provided inside C++ standard library only.

Namespaces can also be nested i.e. one namespace inside other.
Here is an example of nested namespaces

    namespace n3
    {
        int x;
        namespace n4
        {
            int y;
        }
    }

Now as we see, ‘x’ is a variable that belongs to namespace n3 and ‘y’ is a variable that belongs to n4 inside n3.
To access ‘x’, we use n3 :: x;

But to access ‘y’, we use a chain command like
n3 :: n4 :: y;.
Like this, we can handle any level of nesting.

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?