C++ Program to Demonstrate the use of Namespaces

This C++ Program which demonstrates the use of namespaces. The program creates two namespaces with a variable of same name defined in each of them but with different data type. The functions functionOne( ) and functionTwo( ) take an integer as an input and save in the variable “val”. The values of “val” are printed in the context of both namespaces.

Here is source code of the C++ program which demonstrates the use of namespaces. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Demonstrate the use of Namespaces
  3.  */
  4. #include <iostream>
  5.  
  6. namespace One
  7. {
  8.     int val;
  9. }
  10. namespace Two
  11. {
  12.     char val;
  13. }
  14.  
  15. void functionOne(void)
  16. {
  17.     using namespace One;
  18.     /* Variable val is defined in context of namespace One */
  19.     std::cout << "Enter the value of val : ";
  20.     std::cin >> val;
  21.     std::cout << "functionOne()" << endl
  22.               << "Value of val : "
  23.               << val << endl;
  24. }
  25.  
  26. void functionTwo(void)
  27. {
  28.     using namespace Two;
  29.     /* Variable val is defined in context of namespace Two */
  30.     std::cout << "Enter the value of val : ";
  31.     std::cin >> val;
  32.     std::cout << "functionTwo()" << endl
  33.               << "Value of val : "
  34.               << val << endl;
  35. }
  36.  
  37. int main()
  38. {
  39.     functionOne();
  40.     functionTwo();
  41.     return 0;    
  42. }

$ g++ main.cpp
$ ./a.out
Enter the value of val : 5
functionOne()
Value of val : 5
Enter the value of val : 5
functionTwo()
Value of val : &#x2663;

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.