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:
std
namespace, and you have a using namespace std;
statement, you'll get a naming conflict. Using explicit std::
avoids this.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.
Answers to questions are automatically generated and may not have been reviewed.
A quick introduction to namespaces in C++, alongside the standard library and how we can access it