Showing posts with label namespace. Show all posts
Showing posts with label namespace. Show all posts

Tuesday, July 3, 2018

How does namespace declaration helps name resolution?

Identifiers in C++ not being named uniquely leads to problems of name resoultion, inability for the program when ambiguity exists.

This is best seen here:

Namespce_1

Where the header files Test_1.h and Test_2.h are shown:


Namespce_3
 

Namespce_4

and the Namespce.cpp file is this:


Namespce_2

As you can see Test_1.h and Test_2.h have the same name defined, namely Test(int x, int y).

Given this situation, the main() program which is tasked to write to the console Test(5,6) is not able to process.

It throws up with a build error as shown.


Namespce_0

Let us now modify the Test_1.h slightly adding the namespace declaration a shown:


Namespce_5


Now we build and run the program and the following is written to the console.

Namespce_6

This means the program now used Test_2.h to write the above to the screen.

In this case how are we going to use the Test_1.h?

You can do this by using the namespace you declared. Intellisense assists you in doing it as shown. You need to use the scope resolution operator (::).

Namespce_7

Now you build and run, you get the following written to console:


Namespce_8

The example was run on Visual Studio Community 2017, 15.5.7

Saturday, June 30, 2018

Why do you need namespace in a C++ program?

All identifiers in C++ must be unique and, if this rule is not observed in naming you end up with what is called 'naming resolution. The C++ compiler faces an ambiguous situation and, will throw up an error message.

Providing namespace is to help the compiler know that the identifier must be associated with a namespace. This is in much the same was as saying someone lives in Washington (Which one the State or D.C?). It is not a problem with small programs and it becomes a problem for larger programs.

In addition to identifier scope (local, global), namespace provides yet another option to reduce the name conflict in programs.