1 / 6

Namespaces – avoiding naming conflicts

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.

Download Presentation

Namespaces – avoiding naming conflicts

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 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

  3. 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

  4. 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

  5. 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

  6. 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

More Related