Namespace

Namespaces in C++ are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries. We can have namespace inside namespace(Sub-namespace). In order to declare namespace we need to use namespace keyword and we need to give name for it.

In order to access members of a class which is present inside difference namespace. We need to first call the outer most namespace then we need to call sub namespaces then we need to call class then only we can access members of that particular class. We'll see this with code example below

CODE

EG 1 . Creating a namespace with Sub-namespace.

#include <iostream>
using namespace std;

namespace NewlyCreatedNamespace {
    namespace subNamespace1 {
        namespace space {
            class rectangle {
              public:
                double length, width, height;
                double Area() {
                    return length * width;
                }
                double Perimeter() {
                    return 2 * (length + width);
                }
                double Volume() {
                    return Area() * height;
                }
            };
        }
    }
}

//Either we can refer namespace here or we can each time call individual namespaces and access its member(Explained clearly in CODE EXPLANATION).
using namespace NewlyCreatedNamespace::subNamespace1::space;

int main() {
    //We need to give entire directory of namespaces using :: then only we can access class and its members.
    NewlyCreatedNamespace::subNamespace1::space::rectangle wall;
    wall.length = 5;
    wall.width = 6;
    wall.height = 7;
    cout << wall.Area() << endl;
    cout << wall.Volume() << endl;
    cout << wall.Perimeter() << endl;
}



(Click Here, For more exercises)