on Leave a Comment

C++ Namespaces

namespace is a keyword in c++. A namespace is collection of declarations of variables, functions, classes and so on. We know that header files contain declarations of predefined variables, functions etc. But C++ has new feature of containing such declaration in namespaces

But if have a option of header files for containing declaration, then why namespaces. Answer is for solving name collision problem. Suppose we have include two header files in our program and both header files have a declaration of a variable with same name, then name collision problem will occurred. In namespace, if we have same declaration in two different namespaces, so namespace uses some additional information to differentiate declarations.

Syntax of creating namespace

namespace namespace_name
{
   //Declarations
}

Creating namespace

For example:

namespace my_space
{
    int a;
    float b;
    int sum(int x, int y);
    class A
    {
    public:
        void fun();
    };
}

We can also define our own namespace. A namespace only contains declaration statements. A namespace must be defined in global scope or inside other namespace. We can also use alias name for namespace name using namespace keyword. For example,

namespace m = my_space;

If we define two namespaces of similar name, then namespace is extended and considering both namespaces as single namespace. 

Accessing namespace declarations

For example:

namespace my_space
{
    int a;
    float b;
    int sum(int x, int y);
    class A
    {
    public:
        void fun();
    };
}

These declarations can be access using scope resolution operator (::).

For example:

int my_space:: sum(int x, int y)
{
    return x+y;
}
void my_space:: A:: fun()
{
    cout<<"\nHappy Coding";
}

The using directive

To avoid scope resolution operator, we can use using directive

For example:

using namespace my_space;

This tells the compiler that program is using declarations of namespace my_space. 

Example of namespace in c++

#include<iostream>
using namespace std;
namespace my_space
{
    int a;
    float b;
    float sum(int x, float y);
    class A
    {
    public:
        void fun();
    };
}
float my_space:: sum(int x, float y)
{
    return x+y;
}
void my_space:: A:: fun()
{
    cout<<"\nHappy Coding";
}
using namespace my_space;
int main()
{
    a = 10;
    b = 1.5;
    cout<<"a = "<<a;
    cout<<"\nb = "<<b;
    cout<<"\nSum of a and b is "<<sum(a, b);
    A obj;
    obj.fun();
    return 0;
}

OUTPUT:

a = 10
b = 1.5
Sum of a and b is 11.5
Happy Coding




0 comments:

Post a Comment