Raffaele Rossi
Raffaele Rossi

Reputation: 3127

C++ headers and namespaces

I got some confusion in mind between what my professor told us at uni and what I have read in Stroustrup's book.

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

  1. Create equations.h (or whatever)
  2. Create a namespace called eq for example
  3. Put my classes in the namespace

Is this really necassary? Cannot I only use a header file and put all my classes inside?

Upvotes: 1

Views: 1421

Answers (3)

Mikel F
Mikel F

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

tdao
tdao

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

Related Questions