Difference between namespace and class in C++

C++Server Side ProgrammingProgramming

In this section we will see what are the differences between namespace and class in C++. The namespace and classes are two different concepts. Classes are datatypes. Classes are basically extended version of structures. Classes can contain data members and functions as members, but namespaces can contain variables and functions by grouping them into one.

The namespaces cannot be created as objects. This concept is used as additional information to differentiate similar functions, classes, variables etc. Variables, functions with same name can be placed in different namespaces.

Now let us point out some important differences of namespaces and classes.

  • The namespaces are used to make a group of identifiers so they do not clash. By using class, we have to create an instance of that class, but for namespaces this is not true.

  • For namespace we use ‘using’ declaration. For classes it is not possible unless we are deriving from it.

  • We can reopen namespace and add more elements across translation units. This cannot be done using classes.

namespace my_namespace {
   int function1();
}
namespace my_namespace {
   int function1();
}
  • For Class the following code is not fine:

class my_class {
   int function1();
};
class my_class {
   int function1();
};
  • We can use unnamed namespaces, that are fine, but we cannot use unnamed classes That will create error.

namespace{ //Legal
   int function1();
};
class { //create error
   int function1();
};
raja
Published on 03-Apr-2019 16:56:07
Advertisements