Reputation: 3127
I got some confusion in mind between what my professor told us at uni and what I have read in Stroustrup's book.
We all know that a C++ header
is basically a collection of
declarations (defined in a file.h) and they can contain for example a
collection of classes. They are very useful because they give us a
lot of features stored in a single space
A namespace is someting invented to organize classes, functions, types (...) in a part of the program without defining a type.
I cannot see the concrete difference here when I have to create a project.
If I had (for example) to make a program that solves equations of various degrees, I'd put the classes that I need in a single file. For example I am going to place in equations.h
all this stuff: class secondDeg, class thirdDeg, class fourthDeg and so on.
Why should I use a namespace then?
The answer (I guess) is: because you can give a name for a better organization (see std::cin). But in this case I should
eq
for exampleIs this really necassary? Cannot I only use a header file and put all my classes inside?
Upvotes: 1
Views: 1421
Reputation: 3656
You seem to be conflating two distinct concepts. A header is a file, typically used to contain declarations. It can contain function declarations, classes, templates, etc.
A namespace is a means of defining a scope, within which all items declared are unique. This allows you to use function and class names that might otherwise clash with names in the standard. For example
namespace mystuff
{
class list { };
};
Your list will not conflict with std::list.
Namespaces can and should be used in header files to declare the classes and such that are part of that namespace. However, as noted by others, using a 'using' directive in a header file is discouraged because it can create the very name conflicts the namespace was intended to solve.
Upvotes: 3
Reputation: 1
Is this really necassary?
It depends. The better and more clear option would be to embed your declarations in a namespace
.
Cannot I only use a header file and put all my classes inside?
Sure you can, just avoid any clashes with symbols declared in the global (::
) scope and refrain from using namespace <xxx>;
in header files.
Upvotes: 6
Reputation: 17678
Why should I use a namespace then?
A namespace can encompass multiple headers, eg., namespace std
encompasses definitions from <vector>
<list>
etc.
You can define your own namespace
to not pollute the global namespace and avoid conflicts. It's good practice to limit the namespace to the minimum for what you need, therefore using namespace std;
is generally avoided.
Upvotes: 7