c++ basics

Started by
14 comments, last by DejaimeNeto 9 years, 9 months ago

Just to clarify what previous post is telling:

"using namespace std;"

... don't do that. Especially as a beginner - one benefits from clean namespace (not polluted with bazillion things a beginner does not even know exists from std and will bite him in the back). Etc: http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice

I, personally, have never seen a necessity for "using namespace whatever" and consequently have never used it.

Advertisement

Thanks for clarifying that. I wanted to write more, but posting from a phone is so frustrating. ;)

Just out of curiosity. What do you C++ users think of this (using declaration vs. using directive). Is it still bad practice ?


#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;
// etc.
Edit: Meh, it's discussed in that SO thread too. Should have read first. I apologize.

1: If you want to use strings ( or don't want to write overly complex code to handle strings ) , better memorize these 2 lines of code


It's not really a good idea to tell a beginner to use a line of code that it's generally considered bad practice to use.
I think I'll thank to my first C++ book (from Sams, I later found out their books are considered bad) for not telling me to add that statement.
A C++ programming beginner from Malaysia.

Thanks everyone!

using namespace std; // some folks don't like using it due to "conflicts"

It is definitely not about liking or not, I have already seen 4 threads of people asking for help fixing bugs caused by this. One had a variable called max inside a class but, since they had this line in their code, were actually referring to std::max. Also seen this happen with one that had a type called map to store the game map.

Even though we are lucky and the std namespace doesn't have that many typenames that we can conflict with (who'd create a type called basic_string?), this also applies to libraries that have their own namespace. Libraries with a lot of legacy code, or sometimes to comply with ANSI C, doesn't have namespaces; but it is getting more and more common to see libraries that do have.

When you make use of this using statement to bring the entire namespace into the global scope you kill the very reason they added it in the first place...

Just out of curiosity. What do you C++ users think of this (using declaration vs. using directive). Is it still bad practice ?

It is surely better, but even in this case one should never add this in a header file.

This topic is closed to new replies.

Advertisement