Explicit std:: Namespace
Why do you use explicit std:: namespace qualifiers in this lesson's code examples instead of 'using namespace std;'?
In this lesson, I use explicit std:: namespace qualifiers for types and objects from the C++ Standard Library, like std::cout and std::string, instead of a using namespace std; statement. There are a few reasons for this:
- It makes it clear that these types and objects are from the Standard Library and not from the current project or some other library.
- It avoids potential naming conflicts. If your code defines a function or variable with the same name as something in the
stdnamespace, and you have ausing namespace std;statement, you'll get a naming conflict. Using explicitstd::avoids this. - It's considered good practice in many codebases and style guides. While
using namespace std;can be convenient for small examples or personal projects, it's often discouraged in larger codebases or when writing libraries.
For example, instead of:
#include <iostream>
using namespace std;
int main() {
string message = "Hello, world!";
cout << message << endl;
}I would write:
#include <iostream>
int main() {
std::string message = "Hello, world!";
std::cout << message << std::endl;
}The explicit std:: makes it clear where string, cout, and endl are coming from.
There are situations where a using statement can be appropriate, like within a limited scope such as a function, but for clarity and to promote good habits, I generally avoid using namespace std; in examples.
Namespaces, Includes, and the Standard Library
A quick introduction to namespaces in C++, alongside the standard library and how we can access it