The Pros and Cons of the "using" Statement

As part of the lecture, I’ll try to explain the risk of the “using” statement, but I also want to make it clear why it’s a good thing (because I personally like using the “using” statement)

The main purpose of the using directive is to pull in a namespace into the scope of the file. In other words, your file will have access to all of the methods, variables, and types in the “std” namespace without having to write std:: every time you want to use something in the std namespace. This can help clean up your code and let you and others quickly see what namespaces your file is referencing, especially if you’re going to be using a lot of the code from that namespace.

The risk comes from the situation where other namespaces have a method or variable with the same name. If you use the “using” directive on namespaces that have similarly named methods, then the compiler will break and throw an error because it doesn’t know which method to reference. I’m not sure how much of the standard library is used in an actual game, but if you are only going to use a small portion of the namespace, you can write using std::cout; so that only the “cout” method is accessible without the std:: prefix. I think this is something to keep in mind when including you’re own header files into cpp files.

There’s a bit more on namespaces in C++ here: https://msdn.microsoft.com/en-us/library/5cb46ksf.aspx

1 Like

Privacy & Terms