I am attempting to find out what "#include <iostream>" and "using namespace std;" accomplish |
Anytime you
#include
something, you're telling the preprocessor (big word, don't sweat it) to treat the contents of the file you're including as if they had appeared in the source program at the point where you included them.
The reason you'd want to do this, is so that you can write code in more than one file, and include it where other code in other files might need to know what you've written elsewhere.
Why would you want to break up your project into multiple files? Several reasons, I'll just redirect you to this article:
http://www.cplusplus.com/forum/articles/10627/
Now, on to namespaces.
I guess you could say that a namespace is just a convenient way of "grouping" things together that belong together. Just for the sake of example, let's say I'm writing an arithmetic library. I've written some some functions such as
subtract()
and
add()
. I then publish the library, and anyone who wants to use it, can. But Oh no! What if one of my users links my library with their project, and they already have a
subtract()
function of their own? We can't have clashing names. This is an example of when you might want to use a namespace.
In my case, I could simply put all my arithmetic related functions into their own namespace.
Here are my functions in the "global namespace":
1 2 3 4 5 6 7
|
int subtract(int a, int b) {
//Do things
}
int add(int a, int b) {
//Do things
}
|
Here they are in my arithmetic namespace, which I've elected to name "ar".
1 2 3 4 5 6 7 8 9 10
|
namespace ar {
int subtract(int a, int b) {
// Do things
}
int add(int a, int b) {
// Do things
}
}
|
This way, anyone who uses my arithmetic functions, can have their own subtract or add functions, without clashing identifiers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <iostream>
#include "arithmetic_header.h"//include my arithmetic header; part of my library!
int subtract(int a, int b) {
// This is the function with the same name, that the user wrote.
// Do something else
}
int main() {
int a = subtract(1, 2); // Call user defined function
int b = ar::subtract(1, 2); // Call to my library defined function
std::cin.get();
return 0;
}
|
This is super simplified, but I hope you got the idea. If there's anything confusing, feel free to ask.