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

No comments: