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.
/*
* C++ Program to Demonstrate the use of Namespaces
*/
#include <iostream>
namespace One
{
int val;
}
namespace Two
{
char val;
}
void functionOne(void)
{
using namespace One;
/* Variable val is defined in context of namespace One */
std::cout << "Enter the value of val : ";
std::cin >> val;
std::cout << "functionOne()" << endl
<< "Value of val : "
<< val << endl;
}
void functionTwo(void)
{
using namespace Two;
/* Variable val is defined in context of namespace Two */
std::cout << "Enter the value of val : ";
std::cin >> val;
std::cout << "functionTwo()" << endl
<< "Value of val : "
<< val << endl;
}
int main()
{
functionOne();
functionTwo();
return 0;
}
$ 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 : ♣
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]Related Posts:
- Check C++ Books
- Check Computer Science Books
- Practice Programming MCQs
- Apply for Computer Science Internship
- Apply for C++ Internship