I figured I might address this, in case some students come in and might have got a shortcut for this from a friend or co-worker.
There does exist a sort-of ‘bad practice’ for coding where you use the following code:
#include
using namespace std;
What this essentially does is allow you to declare that you are using the namespace ‘std’ in this code from the string library. This would allow you to declare the string variables without having to use the std and scope resolution operator. So instead of:
std::string knightHealth = "Health: ";
We can use:
string knightHealth = "Health: ";
Anywhere we need to access a function with scope resolution, we can ignore the std declaration.
HOWEVER…this is bad practice for the following reasons:
If something changes with functions in the standard library, or say some code is created that later changes the way a standard library function behaves, this could most definitely break your code that you may have typed years ago. The reason being is that using ‘namespace’ imports the entirety of the std namespace into the current namespace of the program.
“Namespaces were introduced into C++ to resolve identifier name conflicts. This ensured that two objects can have the same name and yet be treated differently if they belonged to different namespaces. When we import a namespace we are essentially pulling all type definitions into the current scope. The std namespace is huge. It has hundreds of predefined identifiers, so it is possible that a developer may overlook the fact there is another definition of their intended object in the std library”.
So while it may be tempting to save some typing and make the code look cleaner or easier to read, it is not a good idea to declare the use of a namespace and instead simply use the scope resolution operator to tell the compiler where you are getting your namespaces.
If I am off on my information, someone feel free to correct or add to this.
-C