Related
I am trying to understand namespace std. I know what a namespace is. I want to know, is namespace std defined in multiple header files?
I have two sample codes here, and they both compile and run fine. One uses #include<string> and the other uses #include<iostream>. Both use "using namespace std". This tells me that std is defined in both headers, is that right? If so, then when I use both headers in the same code, how will the compiler know which std to use?
CODE 1:
#include <string>
using namespace std;
int main()
{
string test;
test = "hello";
return 0;
}
CODE 2:
#include <iostream>
using namespace std;
int main()
{
string test;
test = "hello";
return 0;
}
A namespace is open; that is, you can add names to it from several separate namespace declarations. For example:
namespace A {
int f();
}
namespace A {
int g();
}
All namespaces with the same name (and in the same scope) are unified to one, so the compiler doesn’t have to choose.
"this tells me that std is defined in both the headers. is that
right?"
The headers include parts of the standard library. Both, iostream and string belong to the standard library, and each of them provides a different set of commands that can be addressed with std::.
The insertion of using namespace resolves the scope, which means that the compiler searches for a function or a command within std::: if it is not found in an inner scope. Therefore, instead of, e.g., writing std::cout << "Hello world" << std::endl; you can simply write cout << "Hello world" << endl; (assuming that iostream is included). This shortens and simplifies the writing of the code, but it can also have disadvantages, which is why using namespace std is generally considered bad practice.
Some headers of the standard library are included indirectly when another header is included. This appears to be the case in your Code2, which compiles although #include<string> is missing.
One cannot rely on such indirect inclusions. More information on this topic can be found here:
Do I have to use #include <string> beside <iostream>?
I know what a namespace is.
Perhaps you do, perhaps not exactly. A namespace is a tool used to prevent naming conflicts. Everything belonging (directly) to a namespace is public, as public identifiers are the only ones that can conflict with code outside the namespace. Unlike a class, there is no encapsulation or data integrity concerns to address; such concerns are relegated to the classes within the namespace.
This open nature of namespaces means that, unlike class definitions, a namespace definition need not be complete. All you need is for (the teams working on) the pieces of the namespace to coordinate their naming schemes. This is why it is typically wrong to add something to someone else's namespace. Since you are not part of the coordination, you could inadvertently introduce a conflict, perhaps quietly introducing undefined behavior, no diagnostic required.
Syntactically, though, you can add to any namespace. This is a useful feature, since traditionally one creates a header file for each class, and namespaces often span more than one class. So it is often desired for a namespace to span multiple header files. How to use namespace across several files? Just use the same namespace name in each namespace definition. A namespace definition is not so much a "definition" as it is a "tour". It is more "this is part of the namespace" than "this is the namespace". The more tours/parts you see, the more complete your view.
On the subject of incomplete views of a namespace, see Can the definition of a namespace span multiple translation units? (Hopefully you guessed "yes".)
I want to know, is namespace std defined in multiple header files?
Yes. The C++ standard dictates dozens of header files that must exist, and implementations are allowed to break those into auxiliary headers. See cppreference.com for a list of the required headers; the ones listed before the "C compatibility headers" section collectively define the std namespace.
Just started collage and I'm new in the world of programming. So, as I was learning C++ I bumped into a question that wouldn't let me be : "Why do i need to include "using namespace std" in my code to be able to write or read if i already got iostream?" , because I've been told that "cin/cout" are already defind in iostream library, but I noticed that if I write one of these lines alone it will give a compilation error. And ,therefore, what's the relation between iostream and "std" namespace ...Can someone explain , please? Thank you! <3
#include vs using
In simple terms:
#include <iostream> // include the header
int main() {
// now you can use stuff declared in that header
std::cout << "Hello world" << std::endl;
// if you are lazy you can "use" things:
using std::cout;
using std::endl;
cout << "Hello World" << endl;
}
You do not have to write using namespace std;! The cases where it is appropriate to do that are so rare and the cases where it really does great harm are so frequent that as a rule of thumb you can remember: Never use it! For details see here: Why is “using namespace std;” considered bad practice?. It is imporant to realize that the difference between fully qualifying a name, std::cout, and not fully qualifying the name, cout, is not just about typing 5 characters more or less (read on...).
libraries vs namespaces
What's the relation between libraries and namespaces?
The standard library puts everything in the std namespace. Namespaces help to keep things separated. A different library can contain a other_namespace::vector and there will be no confusion with std::vector because we have namespaces.
the really cool stuff
One deeper reason to use namespaces is Argument Dependent Lookup. I will try to explain with a simple example. Suppose you are using a library with some function template that does something with objects of a type you will have to supply:
namespace library {
template<typename T>
void do_something(T& a,T& b){
std::cout << "wrong...\n";
std::swap(a,b); // (1)
std::cout << "correct\n";
using std::swap;
swap(a,b); // (2)
}
}
I takes two objects and swaps them twice. You have to bear with me for second to understand why (1) is wrong and only (2) is correct. For now we have a library function template and to use that we need some type T:
namespace A {
struct foo{};
void swap(foo& a,foo& b) {
std::cout << "A::swap" << "\n";
}
}
Imagine foo is such that we know a better way than std::swap to swap to instances. Actually foo is empty, so to swap two objects we have to do nothing.
Lets recap: There is std::swap that comes with the standard library. Someone wrote a library (called library) we want to use. We want the library code to call A::swap instead of std::swap. The library author doesn't even know that A::swap exists.
Together with above A and library, this code
int main() {
A::foo a,b;
library::do_something(a,b);
}
will print:
wrong...
correct
A::swap
Live Example. What happened? This line:
std::swap(a,b); // (1)
calls std::swap, no doubt. Not what we want. We would like the library code to call our A::swap.
Now this:
using std::swap;
swap(a,b); // (2)
The first line pulls the name swap from std into the scope of the function. In the second line finally ADL kicks in because it says swap not std::swap. ADL in a nutshell is: a and b are from namespace A, so when the compiler searches for all possible swaps it also searches in A. If it finds one in A then it calls that (and if it does not find one in A there is still the swap coming from std). Hence only (2) calls our custom swap.
This can only work with namespaces. The "cool stuff" is that the library author does not need to know anything about your namespace but still their library code will call your function from your namespace if it exists.
I should note that not all code is generic library code. Often you want to write code where you know what happens in each detail, you want to know what functions get called. Often you do not want your code behave differently depending on a specific header being included or not. Hence, lots of code is better off with fully qualifiying function calls: std::foo.
conclusion
I hope that I could convince you that namespaces is not just about typing some characters more or less. using namespace std; for lazyness completly misses the point of namespaces. On the other hand, pulling names into scope via using std::foo; foo(); is
completely fine and enables ADL.
Libraries and namespaces are related by convention.
By convention, the symbols that a library provides to the programmer-user are contained in a namespace. This organizes things, and there are some higher level language features (ADL) that mean code in a namespace behaves differently than code outside of it.
When you type using namespace std; you tell the compiler "when you run into a symbol, also look into std to find if you can determine what it is". It is generally a really really bad idea to do this at "file" scope; doing it within a single short function is usable, but any more than that can lead to really tricky bugs.
The standard, professional way to interact with namespace std is to prefix your symbols with the namespace:
std::cout << "Hello world\n";
rather than
using namespace std;
cout << "Hello world\n";
and definitely never:
using namespace std;
int main() {
cout << "Hello world\n";
}
you can also grab single symbols, which isn't as bad as importing an entire namespace:
using std::cout;
cout << "Hello world\n";
but should also be avoided at "file" scope.
#include <iostream>
this includes the header file named iostream from the system search path. iostream is part of the standard library. By convention (and the C++ standard), the symbols that iostream provides your program with are located within namespace std.
By putting symbols in a namespace, you avoid conflict with your code. There are many, many symbols in std, and if #include <iostream> shoved some unknown number of symbols into your global namespace, you could easily get errors or the wrong function called in unexpected ways.
std::cout and using namespace std; cout and using std::cout are all ways to tell the compiler in what namespace to find the symbol cout.
#include <iostream> includes cout in namespace std; without it, your code is unaware of its existence.
C++ developed from C, and C has a textual inclusion model. #include actually takes the content of the file iostream and copy/pastes it into your file. Your compiler then reads that extended file and finds the symbols in <iostream>.
Because this textual inclusion could shove a LOT of stuff, having it isolated to a namespace prevents problems for you, the programmer.
Recently, C++ has added modules. Modules are an alternative to #include directives, in that it directly grabs symbols from a library and injects it into your code without a huge copy paste.
In modules, namespaces are still not directly connected to the module. You can
import std;
or
import std.iostream;
and that will just import the std library symbols, still in namespace std, into your code. (the C++ standard added modules, but did not modularize the std library yet, so those names above are speculation).
The symbol lookup is not directly connected to the symbol import.
This lets symbol import be done in large chunks, while lookup be done more carefully.
iostream is a library. It's code someone has written for you so you don't have to do it. By adding #include <iostream> you tell the preprocessor to paste in that code. But the functions and structures that are provided by this code might have names that interfere with others. But that isn't a problem because you can just separate them by putting them in a namespace, the STL(which upstream is part of) does this with std(short for standard, pronounced as 'stood'). When something is in a namespace, you must name that namespace to access stuff in that. i.e. std::cout. But sometimes you don't want to have to write std:: every time you want to access something from the STL. That's what using namespace std does for you. That way, you can just type cout. But this is a very bad idea!
Libraries
Libraries have portions of codes pre-written to provide you with functionalities. Could be in the form of functions/overloaded operators etc.
There are two types of libraries:
Standard Libraries e.g. #include <iostream> and the name of library is in angle brackets.
User defined/made e.g. #include "randomLib.h" and the name of library is in double quotes.
Namespaces
When you require multiple libraries for your project. There is possibility that the both may include multiple methods (function definition) with the same name or a single library may use same function names but in different namespaces. Namespaces are there to remove the confusion or ambiguity for the compiler and user.
Lets say lib 1 has namespace abc{ foo(); } and lib 2 has namespace def{ foo(); }
So you will do abc::foo() or def::foo() for you required functionality. Here abc/def is the namespace, :: is called scope resolution operator and foo() is the method you are calling.
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?
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.
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;
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;
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.
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
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++.
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).
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.
#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.]
You can also contain "using namespace ..." inside a function for example:
void test(const std::string& s) {
using namespace std;
cout << s;
}
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.
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:: .
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.
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.
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.
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.
Why do we need both using namespace and include directives in C++ programs?
For example,
#include <iostream>
using namespace std;
int main() {
cout << "Hello world";
}
Why is it not enough to just have #include <iostream> or just have using namespace std and get rid of the other?
(I am thinking of an analogy with Java, where import java.net.* will import everything from java.net, you don't need to do anything else.)
using directives and include preprocessor directives are two different things. The include roughly corresponds to the CLASSPATH environment variable of Java, or the -cp option of the java virtual machine.
What it does is making the types known to the compiler. Just including <string> for example will make you able to refer to std::string :
#include <string>
#include <iostream>
int main() {
std::cout << std::string("hello, i'm a string");
}
Now, using directives are like import in Java. They make names visible in the scope they appear in, so you don't have to fully qualify them anymore. Like in Java, names used must be known before they can be made visible:
#include <string> // CLASSPATH, or -cp
#include <iostream>
// without import in java you would have to type java.lang.String .
// note it happens that java has a special rule to import java.lang.*
// automatically. but that doesn't happen for other packages
// (java.net for example). But for simplicity, i'm just using java.lang here.
using std::string; // import java.lang.String;
using namespace std; // import java.lang.*;
int main() {
cout << string("hello, i'm a string");
}
It's bad practice to use a using directive in header files, because that means every other source file that happens to include it will see those names using unqualified name lookup. Unlike in Java, where you only make names visible to the package the import line appears in, In C++ it can affect the whole program, if they include that file directly or indirectly.
Be careful when doing it at global scope even in implementation files. Better to use them as local as possible. For namespace std, i never use that. I, and many other people, just always write std:: in front of names. But if you happen to do it, do it like this:
#include <string>
#include <iostream>
int main() {
using namespace std;
cout << string("hello, i'm a string");
}
For what namespaces are and why you need them, please read the proposal Bjarne Stroustrup gave 1993 for adding them to the upcoming C++ Standard. It's well written:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1993/N0262.pdf
In C++ the concepts are separate. This is by design and useful.
You can include things that without namespaces would be ambiguous.
With namespaces you can refer to two different classes that have the same name. Of course in that case you would not use the using directive or if you did you would have to specify the namespace of the other stuff in the namespace you wanted.
Note also that you don't NEED the using - you can just used std::cout or whatever you need to access. You preface the items with the namespace.
In C++ #include and using have different functions.
#include puts the text of the included file into your source file (actually translation unit), namespaces on the other hand are just a mechanism for having unique names so that different people can create a "foo" object.
This comes from C++ not having the concept of a module.
Keep in mind that namespaces in C++ are open, that means that different files can define different parts of the same namespace (sort of like .NET's partial classes).
//a.h
namespace eg {
void foo();
}
//b.h
namespace eg {
void bar();
}
The include is defining the existence of the functions.
The using is making it easier to use them.
cout as defined in iostream is actually named "std::cout".
You could avoid using the namespace by writing.
std::cout << "Hello World";
These keywords are used for different purposes.
The using keyword makes a name from a namespace available for use in the current declarative region. Its mostly for convenience so that you do not have to use the fully qualified name all the time. This page explains it in some detail.
The #include statement is a pre processor directive and it tells the preprocessor to treat the contents of a specified file as if those contents had appeared in the source program at the point where the directive appears. That is, you can think of this statement as copying the included file into the current one. The compiler then compiles the entire file as if you wrote all the code in one big file.
As pointed out, C++ and Java are different languages, and do somewhat different things. Further, C++ is more of a 'jest grew' language, and Java more of a designed language.
While using namespace std; isn't necessarily a bad idea, using it for all namespaces will eliminate the whole benefit. Namespaces exist so that you can write modules without regard to name clashes with other modules, and using namespace this; using namespace that; can create ambiguities.
I think the other answers are missing the point slightly. In all of C++, Java and C#, the using/import thing is entirely optional. So that's not different.
And then you have to do something else to make code be visible anyway, in all three platforms.
In C++, you minimally have to include it into the current translation unit (good enough for many implementations of vector, string, etc.), often you have to add something to your linker as well, although some libraries do that automatically based on the include (e.g. boost when building on Windows).
And in C# you have to add a reference to the other assembly. That takes care of the equivalent of includes and link settings.
And in Java you have to ensure the code is on the classpath, e.g. adding the relevant jar to it.
So there are very closely analogous things required on all three platforms, and the separation between using/import (a convenience) and actual linkage resolution (a requirement) is the same in all three.
You need to understand namespaces if you want to truly understand this.
With include you are just including the header file.
With using namespace you are declaring you are using a given namespace that contains stuff such as cout. so if you do this:
using namespace std;
to you use cout you can just do
cout << "Namespaces are good Fun";
instead of:
std::cout << "Namespaces are Awesome";
Note that if you do not #include <iostream> you won't be able to use neither std::cout nor cout in your declarations and so forth because you're not including the header.
One liner (not that this is something new :)):
using std allows you to omit std:: prefix, but you cannot use cout at all without iostream.
Even Stroustrup refers to the #include mechanism as somewhat hackish. However it does make separate compilation much easier (ship compiled libraries and headers instead of all source code).
The question really is "why did C++ -- after it already had the #include mechanism -- add namespaces?"
The best example I know of about why #include isn't enough comes from Sun. Apparently Sun developers had some trouble with one of their products because they had written a mktemp() function that happened to have the same signature as a mktemp() function that was included through from a file that was itself included through a header the project actually wanted.
Of course the two functions were not compatible, and one could not be used as a substitute for the other. On the other hand, the compiler and linker did not realize this when building the binary, and sometimes mktemp() would call one function, and sometimes it would call another, based on the order different files were compiled or linked.
The problem stems from the fact that C++ was originally compatible with -- and essentially piggy-backed on top of -- C. And C has only a global namespace. C++ solved this problem -- in code that is not compatible with C -- through namespaces.
Both C# and Java (1) have a namespace mechanism (namespace in C#, package in Java), (2) are usually developed through IDEs that handle referring to binaries for the developer, and (3) don't allow freestanding functions (a class scope is something of a namespace, and reduces the risk of polluting the global namespace) so they have a different solution to this problem. However, it is still possible to have some ambiguity regarding which method you're calling (say, a name clash between two interfaces that a class inherits), and in that case all three languages require the programmer to clearly specify which method they're actually looking for, usually by prepending the parent class/interface name.
In C++, the include directive will copy and paste the header file into your source code in the preprocessing step. It should be noted that a header file generally contains functions and classes declared within a namespace. For example, the <vector> header might look similar to something like this:
namespace std {
template <class T, class Allocator = allocator<T> > class vector;
...
}
Supposing you need to define a vector in your main function, you do #include <vector> and you have the piece of code above in your code now:
namespace std {
template <class T, class Allocator = allocator<T> > class vector;
...
}
int main(){
/*you want to use vector here*/
}
Notice that in your code the vector class is still located in the std namespace. However, your main function is in the default global namespace, so simply including the header will not make the vector class visible in global namespace. You have to either use using or do prefixing like std::vector.
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?
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.
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;
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;
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.
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
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++.
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).
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.
#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.]
You can also contain "using namespace ..." inside a function for example:
void test(const std::string& s) {
using namespace std;
cout << s;
}
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.
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:: .
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.
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.
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.
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.