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.
Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.
- namespace in C++ | Set 2 (Extending namespace and Unnamed namespace)
- Namespace in C++ | Set 3 (Accessing, creating header, nesting and aliasing)
- Namespace in C++ | Set 1 (Introduction)
- Cons of using the whole namespace in C++
- Why "using namespace std" is considered bad practice
- Difference between Abstract Class and Concrete Class in Java
- Difference between Base class and Derived class in C++
- Difference between Anonymous Inner Class and Lambda Expression
- Difference between Shallow and Deep copy of a class
- How to convert a class to another class type in C++?
- Differences between Interface and Class in Java
- Difference between Stop and Wait protocol and Sliding Window protocol
- Similarities and Difference between Java and C++
- Difference between Yaacomo and and XAP
- Difference between VoIP and and POTS
- Difference and Similarities between PHP and C
- Difference between Time Tracking and Time and Attendance Software
- Difference Between Single and Double Quotes in Shell Script and Linux
- C++ string class and its applications
- C++ String Class and its Applications | Set 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.