Difference between namespace and class

Classes are data types. They are an expanded concept of structures, they can contain data members, but they can also contain functions as members whereas a namespace is simply an abstract way of grouping items together. A namespace cannot be created as an object; think of it more as a naming convention. It is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. In essence, a namespace defines a scope.Following are some points to justify :

1. A namespace is a way of grouping identifiers so that they don’t clash. Using a class implies that you can create an instance of that class, not true with namespaces.

2. You can use using-declarations with namespaces, and that’s not possible with classes unless you derive from them.



3. You can reopen a namespace and add stuff across translation units. You cannot do this with classes.For example:-

filter_none

edit
close

play_arrow

link
brightness_4
code

namespace A {
int f1();
}
  
namespace A {
int f2();
}

chevron_right


is legal, but:

filter_none

edit
close

play_arrow

link
brightness_4
code

class A {
    int f1();
};
  
class A { // illegal
    int f2();
};

chevron_right


is not.

4.You can have unnamed namespaces but you can’t have a unnamed class.For example:

filter_none

edit
close

play_arrow

link
brightness_4
code

namespace { // fine
  
// some code....
}
  
class { // illegal
}

chevron_right


5. If length of a name makes code difficult to read, or is tedious to type in a header file where using directives can’t be used, we can make a namespace alias which serves as an abbreviation for the actual name. For example:

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
  
namespace foo {
    namespace bar {
        namespace baz {
            int qux = 42;
        }
    }
}
  
namespace fbz = foo::bar::baz;
  
int main()
{
    std::cout << fbz::qux << '\n';
}

chevron_right


Output :

 42 

In case of class we have to use typedef.

filter_none

edit
close

play_arrow

link
brightness_4
code

class Car {
public:
    typedef std::vector<Wheel> WheelCollection;
    WheelCollection wheels;
};

chevron_right




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.