Quote:
Originally Posted by Ryanb9
correct me if im wrong, but library's the things you put at the top? if so ive been learning / using these so far:
#include "stdafx.h"
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <string>
Yah, the first three includes are C standard library (stdlib) header files which basically tell the compiler to insert all of the functions/classes declared in the headers. The last two are C++ stdlib headers.
Quote:
the main thing im worried about is learning something I shouldn't be learning for fear of developing bad habits. for instance iv been using "using namespace std ; " since i started a week or so ago and and now im reading about how this is horrible because it replaces all instances of something or other
The main problem with just using 'using namespace std;' is that it's easy to pass over learning about how the C++ namespace works. For example, the string object defined in <string> is part of the 'std' namespace, and might be declared like
namespace std {
class String { ... };
}
and you need to use the namespace resolution operator 'std::String' whenever you reference a String object in your code. The 'using namespace std;' statement allows you to just use String without the :: operator, like if I wanted to declare a string object as 'String hello("hello!");' but it also imports every other variable and function name in the std namespace from any included stdlib headers, which might conflict with ones you're using. Not a big deal when you're doing simple programs, but if you're writing something that might include library files that might use the same names, or if your code is part of a library other people will include, you don't want to "pollute" the namespace by introducing all of those std namespace names.
But imagine if you want to make your own String class and for some reason also want to use the stdlib String class, perhaps by extending std::String through inheritance, you can do the following:
class String : public std::String { ... };
Something I typically do if I'm using a single function from a library header, is to use something like 'using std::String;' which has the same effect as 'using namespace std;' without importing all of the names from the library I won't need. It also acts as a form of documentation, where you can look at the top of a source file and see what exactly is being used from any included headers.
It takes a while to get used to how libraries work with C++, particularly when you start using libraries outside the standard library and have to learn about the linking phase of compilation, and the difference between static and dynamic libraries, and it's one of the annoyances of dealing with C++.
Last edited by weevil; 02-20-2012 at 07:48 PM.