Difference between classes and namespaces?
You can search on the web for the differences and i am sure you will find many; but the following are important IMHO:-
- You can reopen a namespace and add stuff across translation units. You cannot do this with classes.
- Using a class implies that you can create an instance of that class, not true with namespaces.
- You can use using-declarations with namespaces, and that's not possible with classes unless you derive from them.
- You can have unnamed namespaces.
A namespace defines a new scope and members of a namespace are said to have namespace scope. They provide a way to avoid name collisions (of variables, types, classes or functions) without the inconvenience of handling nested classes.
Classes and structs define types. You can create an object of a type. Namespaces simply declare a scope inside which other types, functions, objects, or namespaces can exist. You can't create an object of type std
(unless of course you created a type called std
, which would hide the std
namespace).
When you define a function inside a struct/class (a method) you're saying "This function is a fundamental operation on the associated data". When you define a function inside a namespace you're saying "This function is logically related to other functions, types, and objects in the namespace"
Edit
It's probably worth pointing out that "everything is an object" languages like Java and C# regularly use classes as if they were namespaces because they don't allow "free" functions. This may be where the confusion comes from. If you have a class in another language that contains nothing but static members, you would want to use a namespace and free functions in the C++ version.