Well to start let me say that I'm only a newbie, as my status says, but after a year of C++ I have what I consider a pretty good grasp over the basics of the language. I'm still at school for the summer doing an internship and have a lot of extra time so I'm making little applications for our CS department as well using openGL. My problem is not with this as I am able to create and implement whole applications that run well and everything, using classes and all the good elements of C++ OOP like virtual functions and abstract classes, but I'm trying to branch out a little more and discover more of the use of the language.

I realized that we have never really covered namespaces in class or outside of it. All of my projects reside in the humble std namespace and there's no problem with doing it that way, but I was wondering what exactly the use of auxillary namespaces is? The one example I've come up with myself is that it would allow the creation of two identically named variables and then a switching between namespaces to access the proper one depending on the context, but that seems like it would be more easily/simply done with an array. My question is actually two similar questions:

1) Why are namespaces used? What kind of programming makes them extremely useful, or are they used more for a "better" encapsulation than simple classes?

2) Why are namespaces included in the C++ language, specifically what do they "do" for the language?

Number two might be just a slightly different way of asking number 1, but any light more experienced people could shed on namespaces would be greatly appreciated.

Recommended Answers

All 5 Replies

"using namespace std;" is used instead of coding the using the usual ::iostream, cout and cin, endl; It's a shortcut to minimize the extra typing

I understand the reason for "using namespace std;", I was wondering when and why people create their own namespaces. I also realize the syntactical complications that would arise from using a custom namespace, like you said, having to put std:: in front of cout, cin, etc. I was wondering more about the reasons a person would consider using their own namespace, what advantage they would get from it.

what advantage they would get from it.

To avoid name (identifier) clashes.

> I was wondering more about the reasons a person would consider using their own namespace, what advantage they would get from it.
Name conflicts are the most commonly stated reason for using namespaces, but Edward uses them for code organization too. Everything Ed uses for security might be in multiple files but sit in the EdRules::Security namespace to make it clear that all of the files are related to a single top-level goal.

Thank you, that was quite helpful.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.