Sams Teach Yourself C++ in 21 Days

(singke) #1
Creating and Using Namespaces 639

18


LISTING18.1A First Listing Using integerValue


0: // file first.cpp
1: int integerValue = 0 ;
2: int main( ) {
3: int integerValue = 0 ;
4: //...
5: return 0 ;
6: } ;

LISTING18.1B Second Listing Using integerValue


0: // file second.cpp
1: int integerValue = 0 ;
2: // end of second.cpp

My linker announces the following diagnostic:
in second.obj: integerValue already defined in first.obj.
If these names were in a different scope, the compiler and linker would not complain
about the duplication.
It is also possible to receive a warning from the compiler concerning identifier hiding.
The compiler should warn, in first.cppin Listing 18.1a, that integerValuein main()
is hidingthe global variable with the same name.
To use the integerValuedeclared outside main(), you must explicitly scope the variable
to global scope. Consider this example in Listings 18.2a and 18.2b, which assigns the
value 10 to the integerValueoutside main()and not to the integerValuedeclared
within main().

LISTING18.2A First Listing for Identifier Hiding


0: // file first.cpp
1: int integerValue = 0 ;
2: int main( )
3: {
4: int integerValue = 0 ;
5: ::integerValue = 10 ; //assign to global “integerValue”
6: //...
7: return 0 ;
8: } ;

ANALYSIS
Free download pdf