/* ** $Id: namespaces.cc 824 2008-03-09 19:23:52Z phf $ ** ** Examples of namespaces. */ // Remember that the iostream stuff is in namespace std! #include // In C++ we can use namespaces to "partition" the // identifiers (names) we use into separate "chunks". // This allows people to use the same identifiers in // different libraries yet combine those libraries // in one program. For example, there is a "cout" in // namespace "std" but we can have something else // called "cout" in a different namespace, "cs120" // for example. namespace cs120 { int cout = 47; } // We can also "add" identifiers into an existing // namespace. This is a Bad Idea (tm) if you don't // "own" the particular namespace. So the following // example, which adds "blabla" to namespace "std" // is not something you usually want to do. However, // for namespaces that you control, it's necessary // to enable this so that pieces of your namespace // can be split into different source files. namespace std { int blabla = 30; } // We can also have a global definition for "cout" here, // no conflict with either std::cout or cs120::cout; it's // in no particular namespace. char* cout = "Bla!"; // Here comes the main function. :-) int main() { // And another one, just for kicks... int cout = cs120::cout; // This "cout" is different from all the other ones we had // so far; it's different for sure from the ones in "std" // and "cs120" above; it's also different from the global // "cout" we defined just a few lines above. // This "cout" will "shadow" the outer one, but we can still // get to that one using a special notation: std::cout << std::cout << std::endl // in std << cs120::cout << std::endl // in cs120 << ::cout << std::endl // the global one << cout << std::endl; // the local one // Completely arbitrary aside: Note that C++ comes with a bool // type already, no need for a separate #include file like we // had in C99. bool aha = true; // And like before, they convert easily... cout = aha; aha = cout; // And let's print them? std::cout << cout << std::endl; std::cout << aha << std::endl; // Everything's okay... :-) return 0; }