60 likes | 149 Views
Namespaces – avoiding naming conflicts. What can you do when you have Two classes with the same name? Two functions with identical overloads? Two global objects with the same name? A real problem All declarations of functions and classes you have written so far are global.
E N D
Namespaces – avoiding naming conflicts • What can you do when you have • Two classes with the same name? • Two functions with identical overloads? • Two global objects with the same name? • A real problem • All declarations of functions and classes you have written so far are global CS-183Dr. Mark L. Hornick
Creating Namespaces • Syntax • namespace NAME {…} • Notes: • NAME is often elaborate/unique to avoid conflicts • We say the items within the { } belong to the namespace CS-183Dr. Mark L. Hornick
Namespace Searching • Default • Compiler searches current namespace that has been defined (if there is one) • Then global namespace (i.e. ::) • We can force other namespaces to be searched • using namespace std; • Everything in std is brought into the current (e.g. global) namespace CS-183Dr. Mark L. Hornick
Limiting the Default Search using namespace std; // common • Suppose you only want to use cout… • Single definitions can be added using std::cout; • Only cout will be added • The rest of std will not CS-183Dr. Mark L. Hornick
Nesting – namespaces can contain namespaces namespace abc { namespace def { const int z = 3; } } namespace ghi { const float z = 7.5; } Both namespaces contain a variable named z CS-183Dr. Mark L. Hornick
Using Nested Namespaces • Without shortcuts int y = abc::def::z; float w = ghi::z; • To favor the int over the float using namespace abc::def; int y = z; float w = ghi::z; • or using abc::def::z; // use only “z” from abc::def int y = z; float w = ghi::z; CS-183Dr. Mark L. Hornick