I come from a c# background where everything has its own namespace, but this practice appears to be uncommon in the c++ world. Should I wrap my code in it’s own namespace, the unnamed namespace, or no namespace?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Many C++ developers do not use namespaces, sadly. When I started with C++, I didn’t use them for a long time, until I came to the conclusion that I can do better using namespaces.
Many libraries work around namespaces by putting prefixes before names. For example, wxWidgets puts the characters ‘wx’ before everything. Qt puts ‘Q’ before everything. It’s nothing really wrong with that, but it requires you to type that prefix all over again, even though when it can be deduced from the context which declarations you mean. Namespaces have a hierarchic order. Names that are lexically closer to the point that reference them are found earlier. So if you reference ‘Window’ within your GUI framework, it will find ‘my::gui::Window’, instead of ‘::Window’.
Namespaces enable some nice features that can’t be used without them. For example, if you put your class into a namespace, you can define free functions within that namespace. You then call the function without putting the namespace in front by importing all names, or selectively only some of them into the current scope (‘using declaration’).
Nowadays, I don’t do any project anymore without using them. They make it so easy not to type the same prefix all over again, but still have good organization and avoidance of name-pollution of the global namespace.