Re: header file and 'using directive'
<subramanian100in@yahoo.com> wrote in message
news:a19fbb18-eb54-4539-b5c0-b7f2b59c24a4@d21g2000prf.googlegroups.com...
: Suppose the following is in Test.h
:
: #ifndef TEST_H
: #define TEST_H
:
: #include <iostream>
: #include <string>
:
: using namespace std;
:
: class Test
: {
: public:
: Test(const string& str) : val(str)
: {
: cout << val << endl;
: }
:
: string val;
: };
: #endif
:
: The above is accepted by the compiler. But generally 'using
: declaration/directives' are not mentioned in header files.
: Why is it so ?
Because they go against the purpose of namespaces, creating
potential name collisions in all compilation units that
include the header.
Consider the following two example files:
//BobsLib.h
namespace BobsLib {
class runtime_error { ... };
...
}
//MySourceFile.cpp
#include "BobsLib.h"
#include "Test.h" // your file above
// My file intensively uses BobsLib
using namespace BobsLib;
void myFunction()
{
try {
//stuff using BobsLib...
}
catch( runtime_error& x ); //## ouch
// runtime_error ambiguous: std::~ or BobsLib::~ ?
}
Basically, but putting a using directive in the global
scope of a header file, you prevent all users of that
header from safely using that feature in their own code.
Not nice.
I hope this helps,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com