Difference between namespace and class (original) (raw)

Last Updated : 9 Nov, 2022

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:-

CPP `

namespace A { int f1(); }

namespace A { int f2(); }

`

is legal, but:

CPP `

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:

CPP `

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:

CPP `

#include

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.

CPP `

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

`