Originally Posted by
homeyg
Now I understand that namespaces simply deal with the names that are available, is this correct?
Namespaces are essentially a grouping of names. The namespace name coupled with the name of whatever you're working with is unambiguous. If you don't specify the namespace, it can be ambiguous.
Originally Posted by
homeyg
Putting a using directive in multiple files for a namespace containing a function won't cause the function to be defined twice, because the function is only defined in the namespace and the directive only makes the function name available in the files, correct?
All a using directive does is tell the compiler that the particular names it specifies are CANDIDATES when it sees a particular name.
A "using namespace" directive simply tells the compiler that everything in the specified namespace is a candidate for matching a name that is not adorned with the name of the namespace. If a name is encountered that is in two such namespaces, there are two candidates to match it, and the compiler complains about ambiguity.
More specific "using" directives affect particular names (for example "using std::string;" means that std::string is a candidate for matching a name of something that is simply "string")
For example;
Code:
#include <string> // brings in std::string and associated things
namespace X
{
typedef char string[40];
}
using namespace X;
using namespace std;
void func()
{
string x; // ambiguous, as both X::string and std::strings are candidates
std::string y; // OK; std::string is unambiguous
X::string z; // OK; X::string is unambiguous
}
Originally Posted by
homeyg
Another thing I think I was trying to get at by asking the question in the first post was, putting a using directive at file scope only makes the names available for that file, correct?
For source (eg .cpp) files that is true. The compiler does not make leaps of judgement across multiple source files (it does what is referred to as "separate compilation of source files").
What you say is not true of header files (or any files that are #include'd). Place a using namespace directive into a header file almost always ensures that every source file which #include's that header will be affected by the using directive. One reason that using directives at file scope are discouraged in header files is that there is no way to turn off a "using" directive, meaning that a header file which does it can make source code ambiguous, along the lines of my example above.