Programming Language

Meaning of namespace in C++

Before we start to discuss that what actually a namespace is, it would be best to illustrate a simple example of why and when we would require namespaces. Have a look at the following two fictional C++ header files:

// anyheaderfile.h

class Sample { …  };

 

// anyslibfile.h

class Sample { …  };

 

Notice that it would not be possible to use both of the above header files in one program. This is because there are 2 classes having completely same name – “Sample”. Obviously, if we try to use the “Sample” class after incorporating both of the header files, then it would not be evident that which Sample class we are referring to – the one in the anyheaderfile.h file or the one in the anylibfile.h file.

In this case, namespaces can help. First think of namespace as a declarative region that imposes the attachment of an additional identifier to any names asserted inside that region. Since this is the formal definition, so it might be confusing for you. Another example will help in clarifying the concept.
Just memorize that if the “Sample” classes that we displayed above are in different namespaces, then every name will be distinct. This is just due to the namespace identifier’s addition. The following is an example of namespaces in action. 

 

 

C++ Namespace Example

 

// anyheaderfile.h

namespaceanyHeader

{

class Sample { …  };

}

 

// anylibfile.h

namespaceAnyLib

{

class Sample { …  };

}

In the above example, we have namespaces and we can call every“Sample” classes without getting confused that which “Sample” class we are referring– the one in the AnyLib file or the one in the AnyHeader file. In other terms, the class names are not going to clash. However, how do we in reality make those calls utilizing the correct syntax?

Well, here we can make use of the scope resolution operator. You must have seen “::”before in C++. Thus, to access each of those classes utilizing their concerning namespace, it would appear like this:

AnyHeader::Sample

AnyLib::Sample

Therefore, using the namespace allows us to be more “particular” with regards to which Sample class we want to reference. And there is no name clashing and no ambiguity.

Leave a Reply