Why I should using the namespace
instead the class
? Where is the main difference? For example, in JavaScript the namespace
can be emulated by classes. So, what the point to create namespace instead class?

- 303
- 2
- 9
-
4Does this answer your question? [Difference between classes and namespaces?](https://stackoverflow.com/questions/3188156/difference-between-classes-and-namespaces) – Rohan Bari Apr 30 '20 at 17:15
-
You can't create instances of a `namespace`; you can create instances of a `class`. – Thomas Matthews Apr 30 '20 at 17:40
2 Answers
A namespace
is just a way to separate and group identifiers to avoid naming conflicts at compile-time. A class
is an actual type that you can allocate memory for and create instances of.

- 555,201
- 31
- 458
- 770
Consider an analogous question: What is the main difference between an office chair and a train? You can emulate an office chair by sitting on a train. What is the point of using an office chair instead of a train?
Classes are a types. It is possible to instantiate objects of types. For example:
class foo{}; // a class
foo f; // this variable is instance of the class
Namespaces are not types. It is not possible to create instances of namespaces.
Furthermore, it is possible to have template classes:
template<typename T>
struct bar{};
It is not possible to have namespace templates.
On the other hand, it is possible to have anonymous namespaces, and it is possible to bring members of a namespace into another namespace with using
declaration, which is not possible with members of a class.
So, what the point to create namespace instead class?
We need to group names into smaller scopes to avoid name collisions. That is what namespaces are for.
Classes have a scope as well sure, but when we don't need a type, there is no point in defining a class.

- 232,697
- 12
- 197
- 326