<p>I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++.</p>

<p>How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?</p>

[{'answer_id': 41598, 'author': 'Mark Ingram', 'author_id': 986, 'author_profile': 'https://Stackoverflow.com/users/986', 'pm_score': 8, 'selected': True, 'text': '<p>Namespaces are packages essentially. They can be used like this:</p>\n\n<pre><code>namespace MyNamespace\n{\n  class MyClass\n  {\n  };\n}\n</code></pre>\n\n<p>Then in code:</p>\n\n<pre><code>MyNamespace::MyClass* pClass = new MyNamespace::MyClass();\n</code></pre>\n\n<p>Or, if you want to always use a specific namespace, you can do this:</p>\n\n<pre><code>using namespace MyNamespace;\n\nMyClass* pClass = new MyClass();\n</code></pre>\n\n<p><strong>Edit:</strong> Following what <a href="https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41624">bernhardrusch</a> has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed).</p>\n\n<p>And as you asked <a href="https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41615">below</a>, you can use as many namespaces as you like.</p>\n'}, {'answer_id': 41603, 'author': 'Adam Hollidge', 'author_id': 4069, 'author_profile': 'https://Stackoverflow.com/users/4069', 'pm_score': 2, 'selected': False, 'text': '<p>Generally speaking, I create a namespace for a body of code if I believe there might possibly be function or type name conflicts with other libraries. It also helps to brand code, ala <a href="http://www.boost.org/" rel="nofollow noreferrer">boost::</a> .</p>\n'}, {'answer_id': 41604, 'author': 'dmeister', 'author_id': 4194, 'author_profile': 'https://Stackoverflow.com/users/4194', 'pm_score': 2, 'selected': False, 'text': '<p>I prefer using a top-level namespace for the application and sub namespaces for the components.</p>\n\n<p>The way you can use classes from other namespaces is surprisingly very similar to the way in java.\nYou can either use "use NAMESPACE" which is similar to an "import PACKAGE" statement, e.g. use std. Or you specify the package as prefix of the class separated with "::", e.g. std::string. This is similar to "java.lang.String" in Java.</p>\n'}, {'answer_id': 41620, 'author': 'Adam Hollidge', 'author_id': 4069, 'author_profile': 'https://Stackoverflow.com/users/4069', 'pm_score': 3, 'selected': False, 'text': '<p>@<a href="https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41615">marius</a></p>\n\n<p>Yes, you can use several namespaces at a time, eg:</p>\n\n<pre><code>using namespace boost;   \nusing namespace std;  \n\nshared_ptr&lt;int&gt; p(new int(1));   // shared_ptr belongs to boost   \ncout &lt;&lt; "cout belongs to std::" &lt;&lt; endl;   // cout and endl are in std\n</code></pre>\n\n<p>[Feb. 2014 -- (Has it really been that long?): This particular example is now ambiguous, as Joey points out below. Boost and std:: now each have a shared_ptr.]</p>\n'}, {'answer_id': 41622, 'author': 'Staale', 'author_id': 3355, 'author_profile': 'https://Stackoverflow.com/users/3355', 'pm_score': 4, 'selected': False, 'text': '<p>In Java:</p>\n\n<pre><code>package somepackage;\nclass SomeClass {}\n</code></pre>\n\n<p>In C++:</p>\n\n<pre><code>namespace somenamespace {\n    class SomeClass {}\n}\n</code></pre>\n\n<p>And using them, Java:</p>\n\n<pre><code>import somepackage;\n</code></pre>\n\n<p>And C++:</p>\n\n<pre><code>using namespace somenamespace;\n</code></pre>\n\n<p>Also, full names are "somepackge.SomeClass" for Java and "somenamespace::SomeClass" for C++. Using those conventions, you can organize like you are used to in Java, including making matching folder names for namespaces. The folder->package and file->class requirements aren\'t there though, so you can name your folders and classes independently off packages and namespaces.</p>\n'}, {'answer_id': 41624, 'author': 'bernhardrusch', 'author_id': 3056, 'author_profile': 'https://Stackoverflow.com/users/3056', 'pm_score': 7, 'selected': False, 'text': '<p>To avoid saying everything Mark Ingram already said a little tip for using namespaces:</p>\n\n<p>Avoid the "using namespace" directive in header files - this opens the namespace for all parts of the program which import this header file. In implementation files (*.cpp) this is normally no big problem - altough I prefer to use the "using namespace" directive on the function level.</p>\n\n<p>I think namespaces are mostly used to avoid naming conflicts - not necessarily to organize your code structure. I\'d organize C++ programs mainly with header files / the file structure.</p>\n\n<p>Sometimes namespaces are used in bigger C++ projects to hide implementation details.</p>\n\n<p>Additional note to the using directive:\nSome people prefer using "using" just for single elements:    </p>\n\n<pre><code>using std::cout;  \nusing std::endl;\n</code></pre>\n'}, {'answer_id': 41637, 'author': 'OysterD', 'author_id': 2638, 'author_profile': 'https://Stackoverflow.com/users/2638', 'pm_score': 4, 'selected': False, 'text': '<p>Also, note that you can add to a namespace. This is clearer with an example, what I mean is that you can have:</p>\n\n<pre><code>namespace MyNamespace\n{\n    double square(double x) { return x * x; }\n}\n</code></pre>\n\n<p>in a file <code>square.h</code>, and</p>\n\n<pre><code>namespace MyNamespace\n{\n    double cube(double x) { return x * x * x; }\n}\n</code></pre>\n\n<p>in a file <code>cube.h</code>. This defines a single namespace <code>MyNamespace</code> (that is, you can define a single namespace across multiple files).</p>\n'}, {'answer_id': 41642, 'author': 'Kristopher Johnson', 'author_id': 1175, 'author_profile': 'https://Stackoverflow.com/users/1175', 'pm_score': 2, 'selected': False, 'text': "<p>Note that a namespace in C++ really is just a name space.  They don't provide any of the encapsulation that packages do in Java, so you probably won't use them as much.</p>\n"}, {'answer_id': 41682, 'author': 'spoulson', 'author_id': 3347, 'author_profile': 'https://Stackoverflow.com/users/3347', 'pm_score': 2, 'selected': False, 'text': "<p>I've used C++ namespaces the same way I do in C#, Perl, etc.  It's just a semantic separation of symbols between standard library stuff, third party stuff, and my own code.  I would place my own app in one namespace, then a reusable library component in another namespace for separation.</p>\n"}, {'answer_id': 41823, 'author': 'KeithB', 'author_id': 2298, 'author_profile': 'https://Stackoverflow.com/users/2298', 'pm_score': 2, 'selected': False, 'text': '<p>Another difference between java and C++, is that in C++, the namespace hierarchy does not need to mach the filesystem layout.  So I tend to put an entire reusable library in a single namespace, and subsystems within the library in subdirectories:</p>\n\n<pre><code>#include "lib/module1.h"\n#include "lib/module2.h"\n\nlib::class1 *v = new lib::class1();\n</code></pre>\n\n<p>I would only put the subsystems in nested namespaces if there was a possibility of a name conflict.</p>\n'}, {'answer_id': 41860, 'author': 'Shadow2531', 'author_id': 1697, 'author_profile': 'https://Stackoverflow.com/users/1697', 'pm_score': 3, 'selected': False, 'text': '<p>You can also contain "using namespace ..." inside a function for example:</p>\n\n<pre><code>void test(const std::string&amp; s) {\n    using namespace std;\n    cout &lt;&lt; s;\n}\n</code></pre>\n'}, {'answer_id': 47976, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': "<blockquote>\n  <p>Bigger C++ projects I've seen hardly used more than one namespace (e.g. boost library).</p>\n</blockquote>\n\n<p>Actually boost uses tons of namespaces, typically every part of boost has its own namespace for the inner workings and then may put only the public interface in the top-level namespace boost.</p>\n\n<p>Personally I think that the larger a code-base becomes, the more important namespaces become, even within a single application (or library). At work we put each module of our application in its own namespace.</p>\n\n<p>Another use (no pun intended) of namespaces that I use a lot is the anonymous namespace:</p>\n\n<pre><code>namespace {\n  const int CONSTANT = 42;\n}\n</code></pre>\n\n<p>This is basically the same as:</p>\n\n<pre><code>static const int CONSTANT = 42;\n</code></pre>\n\n<p>Using an anonymous namespace (instead of static) is however the recommended way for code and data to be visible only within the current compilation unit in C++.</p>\n"}, {'answer_id': 48008, 'author': 'Vincent Robert', 'author_id': 268, 'author_profile': 'https://Stackoverflow.com/users/268', 'pm_score': 6, 'selected': False, 'text': '<p>Don\'t listen to every people telling you that namespaces are just name-spaces.</p>\n\n<p>They are important because they are considered by the compiler to apply the interface principle. Basically, it can be explained by an example:</p>\n\n<pre><code>namespace ns {\n\nclass A\n{\n};\n\nvoid print(A a)\n{\n}\n\n}\n</code></pre>\n\n<p>If you wanted to print an A object, the code would be this one:</p>\n\n<pre><code>ns::A a;\nprint(a);\n</code></pre>\n\n<p>Note that we didn\'t explicitly mention the namespace when calling the function. This is the interface principle: C++ consider a function taking a type as an argument as being part of the interface for that type, so no need to specify the namespace because the parameter already implied the namespace.</p>\n\n<p>Now why this principle is important? Imagine that the class A author did not provide a print() function for this class. You will have to provide one yourself. As you are a good programmer, you will define this function in your own namespace, or maybe in the global namespace.</p>\n\n<pre><code>namespace ns {\n\nclass A\n{\n};\n\n}\n\nvoid print(A a)\n{\n}\n</code></pre>\n\n<p>And your code can start calling the print(a) function wherever you want. Now imagine that years later, the author decides to provide a print() function, better than yours because he knows the internals of his class and can make a better version than yours.</p>\n\n<p>Then C++ authors decided that his version of the print() function should be used instead of the one provided in another namespace, to respect the interface principle. And that this "upgrade" of the print() function should be as easy as possible, which means that you won\'t have to change every call to the print() function. That\'s why "interface functions" (function in the same namespace as a class) can be called without specifying the namespace in C++.</p>\n\n<p>And that\'s why you should consider a C++ namespace as an "interface" when you use one and keep in mind the interface principle.</p>\n\n<p>If you want better explanation of this behavior, you can refer to the book <a href="http://books.google.fr/books?id=mT7E5gDuW_4C&amp;dq=exceptional+C%2B%2B&amp;pg=PP1&amp;ots=AXUPz0dWnW&amp;sig=DAib0u-zXuY3lGCCUFPtzI33pCQ&amp;hl=fr&amp;sa=X&amp;oi=book_result&amp;resnum=1&amp;ct=result#PPA119,M1" rel="noreferrer">Exceptional C++ from Herb Sutter</a></p>\n'}, {'answer_id': 81602, 'author': 'paercebal', 'author_id': 14089, 'author_profile': 'https://Stackoverflow.com/users/14089', 'pm_score': 6, 'selected': False, 'text': '<p>Vincent Robert is right in his comment <a href="https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#48008">How do you properly use namespaces in C++?</a>.</p>\n<h2>Using namespace</h2>\n<p>Namespaces are used at the very least to help avoid name collision. In Java, this is enforced through the &quot;org.domain&quot; idiom (because it is supposed one won\'t use anything else than his/her own domain name).</p>\n<p>In C++, you could give a namespace to all the code in your module. For example, for a module MyModule.dll, you could give its code the namespace MyModule. I\'ve see elsewhere someone using MyCompany::MyProject::MyModule. I guess this is overkill, but all in all, it seems correct to me.</p>\n<h2>Using &quot;using&quot;</h2>\n<p>Using should be used with great care because it effectively import one (or all) symbols from a namespace into your current namespace.</p>\n<p>This is evil to do it in a header file because your header will pollute every source including it (it reminds me of macros...), and even in a source file, bad style outside a function scope because it will import at global scope the symbols from the namespace.</p>\n<p>The most secure way to use &quot;using&quot; is to  import select symbols:</p>\n<pre><code>void doSomething()\n{\n   using std::string ; // string is now &quot;imported&quot;, at least,\n                       // until the end of the function\n   string a(&quot;Hello World!&quot;) ;\n   std::cout &lt;&lt; a &lt;&lt; std::endl ;\n}\n\nvoid doSomethingElse()\n{\n   using namespace std ; // everything from std is now &quot;imported&quot;, at least,\n                       // until the end of the function\n   string a(&quot;Hello World!&quot;) ;\n   cout &lt;&lt; a &lt;&lt; endl ;\n}\n</code></pre>\n<p>You\'ll see a lot of &quot;using namespace std ;&quot; in tutorial or example codes. The reason is to reduce the number of symbols to make the reading easier, not because it is a good idea.</p>\n<p>&quot;using namespace std ;&quot; is discouraged by Scott Meyers (I don\'t remember exactly which book, but I can find it if necessary).</p>\n<h2>Namespace Composition</h2>\n<p>Namespaces are more than packages. Another example can be found in Bjarne Stroustrup\'s &quot;The C++ Programming Language&quot;.</p>\n<p>In the &quot;Special Edition&quot;, at <strong>8.2.8 Namespace Composition</strong>, he describes how you can merge two namespaces AAA and BBB into another one called CCC. Thus CCC becomes an alias for both AAA and BBB:</p>\n<pre><code>namespace AAA\n{\n   void doSomething() ;\n}\n\nnamespace BBB\n{\n   void doSomethingElse() ;\n}\n\nnamespace CCC\n{\n   using namespace AAA ;\n   using namespace BBB ;\n}\n\nvoid doSomethingAgain()\n{\n   CCC::doSomething() ;\n   CCC::doSomethingElse() ;\n}\n</code></pre>\n<p>You could even import select symbols from different namespaces, to build your own custom namespace interface. I have yet to find a practical use of this, but in theory, it is cool.</p>\n'}, {'answer_id': 1600792, 'author': 'Éric Malenfant', 'author_id': 59781, 'author_profile': 'https://Stackoverflow.com/users/59781', 'pm_score': 6, 'selected': False, 'text': '<p>I did not see any mention of it in the other answers, so here are my 2 Canadian cents:</p>\n\n<p>On the "using namespace" topic, a useful statement is the namespace alias, allowing you to "rename" a namespace, normally to give it a shorter name. For example, instead of:</p>\n\n<pre><code>Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::TheClassName foo;\nSome::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::AnotherClassName bar;\n</code></pre>\n\n<p>you can write:</p>\n\n<pre><code>namespace Shorter = Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally;\nShorter::TheClassName foo;\nShorter::AnotherClassName bar;\n</code></pre>\n'}, {'answer_id': 66744177, 'author': 'nidhi kumari', 'author_id': 15034008, 'author_profile': 'https://Stackoverflow.com/users/15034008', 'pm_score': -1, 'selected': False, 'text': '<p>std  ::  cout</p>\n<p>The\nprefix std:: indicates that the\nnames cout and endl are\ndefined inside the namespace\nnamed std. Namespaces allow\nus to avoidinadvertent collisions\nbetween the names we define\nand uses of those same names\ninside a library. All the names\ndefined by the standard library\nare in the stdnamespace. Writing std::\ncout uses the scope operator\n(the ::operator) to saythat we\nwant to use the name cout\nthat is defined in the\nnamespace std.\nwill show a simpler way to\naccess names from the library.</p>\n'}]
['https://Stackoverflow.com/questions/41590', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1585/']