Users Online

· Guests Online: 49

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

C++ Program to Demonstrate the use of Namespaces

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;

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.74 seconds
10,818,063 unique visits