Making a namespace

I know how to make a namespace i just want to know why someone would. because it just seems like a way to shove a bunch of variables and functions into a compact area.
The point of namespaces is that it allows you to seperate your functions, classes and global variables into a seperate point, so that the compiler doesn't get confused it which foo() you meant.

It helps get rid of problems like this:

1
2
3
4
// Something1.cpp
int foo(void) {
    // Do something
}

1
2
3
4
// Something2.cpp
int foo(void) {
    // Do something else
}

1
2
3
4
5
6
7
8
// main.cpp
int foo(void);      // Forward declare foo

int main() {
    int num;
    num = foo();   // Which foo gets called?
    return 0;
}


Now, obviously you wouldn't do something like that, but as projects get larger and you lose track of functions, it starts to help arranging them in namespaces. In addition, if you start distributing your functions to other people, it means that it doesn't corrupt their functions with the same name, which could otherwise cause a few headaches.

Basically, though they may not seem all that useful to you know, they are actually important and you should get in the habit of using them.
Last edited on
thank you for the fast reply that definitely explains alot
It is more important than that: it also keeps things separate for the linker.

There exist libraries that cannot co-exist in an application because they have internal functions (or external ones) that conflict with internal functions in another library. When the linker gets the name (no namespace!) it must choose which function is desired. Either way, one of the libraries is screwed and the other one's internal state might be boogered in unexpected ways.

Moral: always put all your stuff in a namespace.

A link, much like NT3's, but more detail:
http://www.cplusplus.com/forum/general/13162/#msg63354

Hope this helps.
Topic archived. No new replies allowed.