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:-
namespace A { int f1(); } namespace A { int f2(); } |
is legal, but:
class A { int f1(); }; class A { // illegal int f2(); }; |
is not.
4.You can have unnamed namespaces but you can’t have a unnamed class.For example:
namespace { // fine // some code.... } class { // illegal } |
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:
#include <iostream> namespace foo { namespace bar { namespace baz { int qux = 42; } } } namespace fbz = foo::bar::baz; int main() { std::cout << fbz::qux << '\n'; } |
Output :
42
In case of class we have to use typedef.
class Car { public: typedef std::vector<Wheel> WheelCollection; WheelCollection wheels; }; |
Recommended Posts:
- 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 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.



