Namespace in C++

    If you want to create a special container to hold a set of names, then it is called namespace. It can be a variable name or a function. Generally, it is useful in avoiding name conflicts.

The types of namespaces are listed below.

1. Global Namespace : It can be declared as globally.

2. Standard Namespace (std): it is a built-in one.

3. User-Defined Namespace: User can create the name space.

4. Nested Namespace: The namespace can be nested by itself or with other namespace.

5. Anonymous Namespace: it is a unusual one.

6. Inline Namespace (C++11 and later): it is like a parent- child relationship.

Eg:

#include <iostream> 

namespace Sample1 {

    // Function greet inside namespace Sample1

    void greetIt() {

        std::cout << "Have a nice day!!" << std::endl;

    }

}

namespace Sample2 {

    // Function greet inside namespace Sample2

    void greetIt() {

        std::cout << "It's a happy day" << std::endl;

    }

}

int main() {

    // Use the scope resolution operator (::) to access greetIt() function inside namespace Room1

    Sample1::greetIt(); 

    Sample2::greetIt();

    return 0; 

}

Output:

Have a nice day!!

It's a happy day.

This is the sample namespace.

Next ,let us create a namespace ‘using’ directive

‘using’ directive:

              It makes the compiler to understand that following code is used for a particular namespace.

Program:

#include <iostream>

namespace first_message {

    void s_fun() {

        std::cout << "it is the first message"

            << std::endl;

    }

}

// Using first_message

using namespace first_message;

int main() {

   // Call the method of first_message (s_fun())

    s_fun(); 

    return 0;

}

Output

it is the first message

Hope, you understand the namespace and its usage in c++. Keep Coding!!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

How to write your first XML program?

Java NIO examples to illustrate channels and buffers.