6
Fall 2004 CS-183 Dr. Mark L. Hornick 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

Namespaces – avoiding naming conflicts

Embed Size (px)

DESCRIPTION

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. - PowerPoint PPT Presentation

Citation preview

Page 1: Namespaces – avoiding naming conflicts

Fall 2004 CS-183Dr. Mark L. Hornick

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

Page 2: Namespaces – avoiding naming conflicts

Fall 2004 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

Page 3: Namespaces – avoiding naming conflicts

Fall 2004 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

Page 4: Namespaces – avoiding naming conflicts

Fall 2004 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 addedusing std::cout; Only cout will be added The rest of std will not

Page 5: Namespaces – avoiding naming conflicts

Fall 2004 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

Page 6: Namespaces – avoiding naming conflicts

Fall 2004 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 floatusing namespace abc::def;int y = z;float w = ghi::z;

orusing abc::def::z; // use only “z” from abc::defint y = z; float w = ghi::z;