What are namespaces?
Written by
Namespaces in C++
Suppose in your group of friends, you have two people with the same name, say ‘A’. Now every time you call A they both get confused if you are calling him or the other A. To resolve this anomaly, you start using their full names. Namespaces in C++ work in the same manner.
Namespaces provide a method of preventing name conflicts in large projects. Variables and functions having the same name can be differentiated using namespaces.
For example,
#include <iostream>
using namespace std;
namespace one{
int val = 512;
}
namespace two{
float val = 3.13;
}
int main(){
cout << one::val;
cout << "\n" << two::val;
return 0;
}
Output
512
3.13
More about namespaces:
- Namespaces is a feature of C++ and is not available in C.
- Namespaces can be declared only globally
- Multiple namespace blocks with the same name are allowed
- Namespace declarations can be nested inside another namespace.
- Namespace don’t use access specifiers i.e public, private
- To avoid writing the name of namespace again and again we can use the keyword using that specifies a default namespace over a block it is declared. example, using namespace std;