- Another way to control scope - where an identifier is visible
- Issue: two programmers could easily make a class Point with
different purposes
- namespace: a way to (say) ensure the point used for the UI is
different than the point used for calculating distances between GPS coordinates
- declaring namespaces:
namespace myNames
{
void getData(int&);
};
namespace yourNames
{
void getData(int&);
};
- For example, file
iostream
namespace std {
class istream { ... };
istream cin;
class ostream { ... };
ostream cout;
};
and file string
:
namespace std {
class string { ... };
};
hence the need for using namespace std
or std::cin
, std::string
- defininitions:
namespace myNames
{
void getData(int &x) { ... }
};
void yourNames::getData(int &y) {...}
- calling methods:
int i;
myNames::getData(i);
yourNames::getData(i);
- using function:
using myNames::getData;
All calls to getData now refer to myNames implicitly
- using namespace:
using namespace myNames;
for easy access to everything
- string, cin, cout are all names
in namespace std
- Private versions of these would be silly!
- If code compiles with either a::f or b::f and
correctness depends on which one you use, reconsider your naming scheme!
- Stack overflow: "using namespace" is bad
- Stroustrup: uses using clauses everywhere!