I am beginner at C++, and I have recently been introduced to namespaces like std. However, if functions like cout and endl are defined in the iostream header file, why include the std namespace at all? Or are these functions actually defined in the std namespace? If that is the case, then why include the iostream file?
3 Answers
Namespaces and #include directives are different things:
When you include a header (like iostream) you are telling the preprocessor to treat the contents of the file as if those contents had appeared in the source program at the point where the include appears.
Why use includes instead of just throwing the code right there?
From: http://www.cplusplus.com/forum/articles/10627/
(1) It speeds up compile time. As your program grows, so does your code, and if everything is in a single file, then everything must be fully recompiled every time you make any little change. This might not seem like a big deal for small programs (and it isn't), but when you have a reasonable size project, compile times can take several minutes to compile the entire program. Can you imagine having to wait that long between every minor change?
Compile / wait 8 minutes / "oh crap, forgot a semicolon" / compile / wait 8 minutes / debug / compile / wait 8 minutes / etc
(2) It keeps your code more organized. If you seperate concepts into specific files, it's easier to find the code you are looking for when you want to make modifications (or just look at it to remember how to use it and/or how it works).
(3) It allows you to separate interface from implementation. If you don't understand what that means, don't worry, we'll see it in action throughout this article.
Namespace on the other hand allows you to group classes and functions under a scope. They provide a way to avoid name collisions between those entities without the inconvenience of handling nested classes.
A C++ file can have a namespace within it, and different C++ files can have the same namespace inside of them.
// Header1.h
namespace SomeScope
{
extern int x;
}
// Header2.h
namespace SomeScope
{
extern int y;
}
// Some CPP file
#include "Header1.h" // access to x
SomeScope::x = 5;
#include "Header2.h" // access to y
SomeScope::y = 6;
I hope this helps. Namespaces just act like a place to store various identifiers to avoid name-clashing. SomeScope::x
is an entirely different x
identifier than AnotherScope::x
.