Loading lessons...
Using Declarations and Directives
Using Declarations and Directives
Writing std:: everywhere gets tiresome. C++ has two tools to shorten it - and they work quite differently.
using declaration
A using declaration brings a single name into the current scope:
using std::cout; // now cout works without std::
using std::endl;
cout << "Hello" << endl;
Only the names you list are imported. The rest of std stays qualified.
using directive
A using directive pulls in an entire namespace at once:
using namespace std;
cout << "Hello"; // works, but see below
Now every name in std is visible without qualification. Convenient - and risky.
The risk: name collisions
A using directive dumps many names into your scope, and you can't always predict which ones will clash with your own or with another library:
using namespace std;
using namespace alice; // both might define the same name!
string data; // is this std::string or alice::string?
When two imported namespaces define the same name, you get ambiguity - and it can be a real headache to untangle.
Best practice
- Prefer using declarations (
using std::cout;) over directives when you only need a few names. - In header files, never use
using namespace- it leaks into every file that includes the header. - Many projects avoid
using namespace std;entirely and just writestd::explicitly.
using std::cout; // good: precise and limited
using namespace std; // works, but use with care
TL;DR
- Using declaration:
using std::cout;imports one name. - Using directive:
using namespace std;imports everything. - The directive risks name collisions and ambiguity.
- Prefer precise using declarations.
- Never put a using directive in a header file.