Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is namespace used for, in C++?

Tags:

c++

What is namespace used for, in C++?

using namespace std;
like image 478
Steven Hammons Avatar asked Mar 17 '11 00:03

Steven Hammons


2 Answers

Namespace is used to prevent name conflicts.

For example:

namespace foo {
    class bar {
        //define it
    };
}

namespace baz {
    class bar {
        // define it
    };
}

You now have two classes name bar, that are completely different and separate thanks to the namespacing.

The "using namespace" you show is so that you don't have to specify the namespace to use classes within that namespace. ie std::string becomes string.

like image 146
Myles Avatar answered Sep 21 '22 13:09

Myles


It's used for preventing name confilct, so you may have two classes with the same name in different namespaces.

Also it's used for categorizing your classes, if you have seen the .net framework, you will see that namespaces are used for categorizing the classes. For example, you may define a namespace for the employee classes, and a namespace for the tasks classes, and both namespaces are within a namespace for the company classes, since a namespace may contain sub namespaces.

The same namespace may exist in different files, so using it may be useful because it will make you able to directly use all the classes in the namespaces in every #included file.

That's what I remember for now.

like image 25
Tamer Shlash Avatar answered Sep 20 '22 13:09

Tamer Shlash