Structures, classes, and namespaces

Jun 18, 2008 at 7:44pm
From what I've read, structs, classes, and namespaces are really similar. I can't even tell the difference, so my first question is what is the difference. My second question is when to use them. You can do a lot of things with those three things, but people say using them helps. In general, when does it help to use them?
Jun 18, 2008 at 7:47pm
Structs and Classes are very similar,

Namespaces are completely different. A Namespace is a named region that your code is stored in. So when you use something like cout that is in the std namespace. So it can be called like std::cout or by using namespace std; then using just cout
Jun 18, 2008 at 8:34pm
A namespace is like a surname.

If you say "John, come here," which John responds? If you say "John Jones, come here," then only John Jones (not John Jacob or John Jefferson or etc) responds.

Structs and classes are exactly the same save for one thing: structs are public by default, and classes are private. In actual practice, people still tend to use structs for "plain-old-data", and classes for object types.

Hope this helps.
Jun 18, 2008 at 8:59pm
Ok, so now I understand the difference between a struct and a class. Could you give a specific example of when it would be useful to use a namespace?
Jun 19, 2008 at 12:02am
For small projects, it isn't really.

For medium and large projects, it makes a huge difference.

Suppose you use two libraries: "console.hpp" and "timer.cpp". Both define a function named "pause()".

Which of the two does the linker include in your program? Which of the two do you mean when you say pause() in main()? If you are lucky your compiler (or, if the competing names are buried as static, internal routines in the library, your linker) will complain and refuse to compile your project. If you aren't it will just choose one --with a 50% chance of it being wrong, and having potentially disastrous results.

With a namespace, the compiler and linker can always tell the difference between console::pause() and timers::pause(), and so can you.

Hope this helps.
Last edited on Jun 19, 2008 at 12:03am
Topic archived. No new replies allowed.