243

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++.

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?

Marius
  • 57,995
  • 32
  • 132
  • 151

16 Answers16

175

Namespaces are packages essentially. They can be used like this:

namespace MyNamespace
{
  class MyClass
  {
  };
}

Then in code:

MyNamespace::MyClass* pClass = new MyNamespace::MyClass();

Or, if you want to always use a specific namespace, you can do this:

using namespace MyNamespace;

MyClass* pClass = new MyClass();

Edit: Following what bernhardrusch 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).

And as you asked below, you can use as many namespaces as you like.

NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104
Mark Ingram
  • 71,849
  • 51
  • 176
  • 230
  • 28
    IMO it is better to just get used to prefixing the `std` namespace to symbols rather than using `using` at all. So I always write `std::cout` or `std::string` now because that's what I call them now. I would never just write `cout`. – Tom Savage Dec 05 '09 at 11:41
  • 5
    While this is very true for `std`, I've personally found this much less important when you're dealing with smaller libraries. Often you can just use `using namespace FooBario;`, particularly if you're using a considerable number of types from a library. – jkerian Oct 30 '10 at 05:13
  • 4
    @jkerian, I see your point, but I disagree because name collisions are (in my mind) more likely to come from precisely such small libraries. Most people are careful not to name classes/functions the same as those in STL. That said, I agree that `using namespace X;` should be avoided in header files if possible. – Alan Turing May 28 '11 at 07:22
  • 15
    @LexFridman "Most people are careful not to name classes/functions the same as those in STL" - that is SO NOT TRUE. For example if I were to write some very specialized I/O code for some weird hardware, I would never, ever, use anything else than `mylibrary::endl` for representing my very own special newline sequence. I mean, why invent names? –  Oct 24 '11 at 12:46
  • My compiler still won't recognize the namespace, even though I want to explicitly specify it and I include the file where it is declared. – bgenchel Nov 13 '15 at 00:21
  • I seen someone use: namespace someNamespace { class MyClass; } and then define it: class someNamespace::MyClass : public otherClass { // usual class stuff } What's the purpose of putting MyClass with the namespace at the top of a header? – user1919249 Oct 19 '16 at 16:11
123

To avoid saying everything Mark Ingram already said a little tip for using namespaces:

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.

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.

Sometimes namespaces are used in bigger C++ projects to hide implementation details.

Additional note to the using directive: Some people prefer using "using" just for single elements:

using std::cout;  
using std::endl;
Lazer
  • 90,700
  • 113
  • 281
  • 364
bernhardrusch
  • 11,670
  • 12
  • 48
  • 59
  • 2
    One advantage of "using namespace" at the function level as you suggest rather than at the .cpp file level or namespace {} block level within the .cpp is that it helps greatly with single-compilation-unit builds. "using namespace" is transitive, and applies for namespace A across discrete namespace A {} blocks in the same unit, so for single-compilation-unit builds you quickly end up using everything if they are done at the file or namespace block level. – idij Dec 18 '14 at 17:27
  • `using std::cout;` is a using declaration – Konstantin Apr 19 '15 at 14:24
  • 3
    Is it possible to use _several_ names from a _single_ namespace in a single statement? Something like `using std::cout, std::endl;` or even, `using std::cout, endl;` . – AlQuemist Apr 29 '16 at 10:02
  • It can be ok to use a `using namespace x` in a header if it's within another namespace. It's not something I would recommend in general but it doesn't pollute the global namespace. – Praxeolitic Jun 10 '16 at 10:01
82

I did not see any mention of it in the other answers, so here are my 2 Canadian cents:

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:

Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::TheClassName foo;
Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::AnotherClassName bar;

you can write:

namespace Shorter = Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally;
Shorter::TheClassName foo;
Shorter::AnotherClassName bar;
Éric Malenfant
  • 13,938
  • 1
  • 40
  • 42
82

Vincent Robert is right in his comment How do you properly use namespaces in C++?.

Using namespace

Namespaces are used at the very least to help avoid name collision. In Java, this is enforced through the "org.domain" idiom (because it is supposed one won't use anything else than his/her own domain name).

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.

Using "using"

Using should be used with great care because it effectively import one (or all) symbols from a namespace into your current namespace.

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.

The most secure way to use "using" is to import select symbols:

void doSomething()
{
   using std::string ; // string is now "imported", at least,
                       // until the end of the function
   string a("Hello World!") ;
   std::cout << a << std::endl ;
}

void doSomethingElse()
{
   using namespace std ; // everything from std is now "imported", at least,
                       // until the end of the function
   string a("Hello World!") ;
   cout << a << endl ;
}

You'll see a lot of "using namespace std ;" 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.

"using namespace std ;" is discouraged by Scott Meyers (I don't remember exactly which book, but I can find it if necessary).

Namespace Composition

Namespaces are more than packages. Another example can be found in Bjarne Stroustrup's "The C++ Programming Language".

In the "Special Edition", at 8.2.8 Namespace Composition, 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:

namespace AAA
{
   void doSomething() ;
}

namespace BBB
{
   void doSomethingElse() ;
}

namespace CCC
{
   using namespace AAA ;
   using namespace BBB ;
}

void doSomethingAgain()
{
   CCC::doSomething() ;
   CCC::doSomethingElse() ;
}

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.

Community
  • 1
  • 1
paercebal
  • 81,378
  • 38
  • 130
  • 159
  • Could you clarify, please "give a namespace to all the code in your module"? What is good practise to encapsulate to module. For example I have class of complex numbers and to external functions related to complex numbers. This class and those two functions should be in one namespace? – yanpas Jan 10 '16 at 12:03
  • *You'll see a lot of "using namespace std ;" in tutorial or example codes*.... and the explainers never mention that this is poor practice, yet it is directed at exactly those who are trying to learn. – D.L Jul 01 '23 at 11:06
58

Don't listen to every people telling you that namespaces are just name-spaces.

They are important because they are considered by the compiler to apply the interface principle. Basically, it can be explained by an example:

namespace ns {

class A
{
};

void print(A a)
{
}

}

If you wanted to print an A object, the code would be this one:

ns::A a;
print(a);

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.

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.

namespace ns {

class A
{
};

}

void print(A a)
{
}

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.

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++.

And that's why you should consider a C++ namespace as an "interface" when you use one and keep in mind the interface principle.

If you want better explanation of this behavior, you can refer to the book Exceptional C++ from Herb Sutter

Dan
  • 5,929
  • 6
  • 42
  • 52
Vincent Robert
  • 35,564
  • 14
  • 82
  • 119
  • 25
    You do actually have to change every call to print() if ns::Print is added, but the compiler will flag each call as ambiguous. Silently switching to the new function would be a terrible idea. – Eclipse Oct 25 '08 at 17:39
  • I am wondering now, having what @Vincent have said that you will have to change all calls to print, if autor would provide ns::Print() function, what were you trying to say? That when author added a ns::Print() function, you can just remove your own implementation? Or that you wuill just add using ns::print() using-declaration? Or domething else? Thanks – Vaska el gato Jun 21 '16 at 21:15
36

Bigger C++ projects I've seen hardly used more than one namespace (e.g. boost library).

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.

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.

Another use (no pun intended) of namespaces that I use a lot is the anonymous namespace:

namespace {
  const int CONSTANT = 42;
}

This is basically the same as:

static const int CONSTANT = 42;

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++.

  • 14
    Both of your examples are equivalent to `const int CONSTANT = 42;` because the top-level const in a namespace scope already implies internal linkage. So you don't need the anonymous namespace in this case. – sellibitze Oct 21 '09 at 14:22
20

Also, note that you can add to a namespace. This is clearer with an example, what I mean is that you can have:

namespace MyNamespace
{
    double square(double x) { return x * x; }
}

in a file square.h, and

namespace MyNamespace
{
    double cube(double x) { return x * x * x; }
}

in a file cube.h. This defines a single namespace MyNamespace (that is, you can define a single namespace across multiple files).

perror
  • 7,071
  • 16
  • 58
  • 85
OysterD
  • 6,660
  • 5
  • 34
  • 33
12

In Java:

package somepackage;
class SomeClass {}

In C++:

namespace somenamespace {
    class SomeClass {}
}

And using them, Java:

import somepackage;

And C++:

using namespace somenamespace;

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.

Staale
  • 27,254
  • 23
  • 66
  • 85
6

@marius

Yes, you can use several namespaces at a time, eg:

using namespace boost;   
using namespace std;  

shared_ptr<int> p(new int(1));   // shared_ptr belongs to boost   
cout << "cout belongs to std::" << endl;   // cout and endl are in std

[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.]

Community
  • 1
  • 1
Adam Hollidge
  • 759
  • 6
  • 12
  • 2
    Note that `std` also has `shared_ptr` by now, so using both `boost` and `std` namespaces will clash when you try to use a `shared_ptr`. – Joey Feb 06 '14 at 19:34
  • 2
    This is a good example of why many software houses will discourage importing entire namespaces in this way. It doesn't hurt to always specify the namespace, and if they're too long then making an alias or only important specific classes from the namespace. – paddy Mar 15 '16 at 22:42
5

You can also contain "using namespace ..." inside a function for example:

void test(const std::string& s) {
    using namespace std;
    cout << s;
}
Shadow2531
  • 11,980
  • 5
  • 35
  • 48
4

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.

Kristopher Johnson
  • 81,409
  • 55
  • 245
  • 302
3

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 boost:: .

Adam Hollidge
  • 759
  • 6
  • 12
3

I prefer using a top-level namespace for the application and sub namespaces for the components.

The way you can use classes from other namespaces is surprisingly very similar to the way in java. You 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.

dmeister
  • 34,704
  • 19
  • 73
  • 95
2

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.

spoulson
  • 21,335
  • 15
  • 77
  • 102
2

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:

#include "lib/module1.h"
#include "lib/module2.h"

lib::class1 *v = new lib::class1();

I would only put the subsystems in nested namespaces if there was a possibility of a name conflict.

Nick
  • 9,962
  • 4
  • 42
  • 80
KeithB
  • 16,577
  • 3
  • 41
  • 45
-1

std :: cout

The prefix std:: indicates that the names cout and endl are defined inside the namespace named std. Namespaces allow us to avoidinadvertent collisions between the names we define and uses of those same names inside a library. All the names defined by the standard library are in the stdnamespace. Writing std:: cout uses the scope operator (the ::operator) to saythat we want to use the name cout that is defined in the namespace std. will show a simpler way to access names from the library.