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:-
is legal, but:
4.You can have unnamed namespaces but you can’t have a unnamed class.For example:
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:
In case of class we have to use typedef.
- namespace in C++ | Set 2 (Extending namespace and Unnamed namespace)
- Difference between Abstract Class and Concrete Class in Java
- Namespace in C++ | Set 1 (Introduction)
- Cons of using the whole namespace in C++
- Why "using namespace std" is considered bad practice
- Difference between Anonymous Inner Class and Lambda Expression
- Namespace in C++ | Set 3 (Accessing, creating header, nesting and aliasing)
- How to convert a class to another class type in C++?
- std::any Class in C++
- Structure vs class in C++
- std::string class in C++
- std::uniform_int_distribution class in C++
- Array class in C++
- std:: valarray class in C++
- Friend class and function in C++
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.