- Namespace in C++ | Set 1 (Introduction)
- Namespace in C++ | Set 2 (Extending namespace and Unnamed namespace)
- Namespace in C++ | Set 3 (Accessing, creating header, nesting and aliasing)
In this article, we will discuss the concept of data sharing between different namespaces, how to access and Overload standard operators to work for user-defined classes inside user-defined namespaces, and their implementation.
In C++, We can create classes inside different namespaces and the scope of those classes is limited to the namespace in which they are created. Hence we must access those classes using the scope resolution operator (::).
Below is the implementation to understand the declaration of classes inside a namespace and initialization of objects in the program:
This is not from (GeeksforGeeks::string) class! Hello! From namespace Test!
In the above program, we can clearly see that scope of the class ‘string’ inside GeeksforGeeks namespace was only inside the namespace and the class was initialized by the parameterized constructor which also changed the private string ‘s’ of Class string inside the namespace Test.
The below program is the illustration of the Concepts of Overloading of Operators with different namespace Class Objects as Parameters and Accessing and Exchange of data from one namespace to another namespace:
This is a standard string (test_space1::string) This is a test_space1 namespace string (test_space2::string) This is a test_space2 namespace string (test_space3::string) Accessing from both namespaces test_space3 and test_space2!
- In the above program, We have created three namespaces – test_space1, test_space2 and test_space3.
- All of these namespaces have a common class string in them. We have created their respective objects s2, s3 and s4 which take different parameters during initialization.
- The namespace test_space3 is used to access class members from inside the string class of namespace test_space2 and hence, test_space3::string’s constructor is different from the other two classes constructors.
- So, We are able to access the data from test_space2 and use it in test_space3. This shows the Accessibility and Exchange of Data between different Namespaces and their Classes.