Are there advantages to using namespaces over classes?


Keywords:c++ 


Question: 

It seems that classes provide a scope for variables and functions, essentially letting it do everything namespaces do.

Am I wrong about this?

If not, why are namespaces used over classes?


3 Answers: 

It's two different purposes.

A namespace is there to avoid naming conflicts, to hide some names to the outside world, and eventually to help in assembling components (when namespace and their aliases are used to address different libraries, e.g boost::regex vs. std::regex).

A class is there to be instantiated and create objects. A variable in a namespace exists only once. A non static data member in a class exists once for each instantiated object. So it's more than just encapsulation and access control.



If you have a class which consist of static member functions only, they appear very similar to namespaces

class A {
    static void foo();
}

can be used A::foo();

If you use a namespace

namespace B {
    void bar();
}

this will also be used as B::bar();

Classes and namespaces both are uniquely defining the name of a function (see name mangling).

Now, the similarities are done. Classes are the fundamental organisation unit in object oriented programming. They encapsulate data and logic operating on this data and hide everything (e.g. it's data and private methods) which is not crucial for the user of the class.

One very important property of a class is, that you create objects form it. Normally you create several objects form one class. This cannot be done with namespaces.



You can't specialize templates in class scope for one, among many.

class C
{
    template<typename> struct S;
    template<> struct S<int> {};  // error
};

More importantly, usage of language features indicates meaning, using something familiar and easy to understand has value on its own.