// namespace-main-1-2.cpp By: Aiman Hanna - ©1993-2006 Aiman Hanna // This program illustrates why namespaces are needed. // By default, every object, function, type or template declared in global scope, // also called global namespace scope, introduces a global entity. Each global entity // that is introduced in the global namespace scope must have a unique name. A function // and object, for example, cannot have the same name, whether or not they are declared // in the same program text file. // When create names, programmers must then make sure that their names will not conflict // with other names from the libraries in which they will link to; otherwise name clashing // occurs. This name clashing problem is referred to as "global namespace pollution problem". // Namespaces can be used to avoid these problems. // In fact, this program does not show anything about namespaces; rather it illustrates // why they are needed. // // Key points: 1) Namespace // 2) Global namespace scope // 3) Global namespace pollution problem #include "namespace1.h" #include "namespace2.h" int main() { Calc1 c1(22), c11(45); c1.setValue(24); Calc2 c2; c2.setValue(c1); cout << "The value of object \"c2\" has been set to : " << c2.getValue(); // use the global object - set it to the same value as c1 dup.setValue(c1); cout << "The value of object \"dup\" has been set to : " << dup.getValue(); // Errors will still occur whether or not the dup method is called // Uncomment-out the following two lines and recompile // dup(c1, c11); // cout << "The value of object \"c1\" has been set to : " << c1.getValue() << endl; return 0; } // The result of compiling the program /* --------------------Configuration: namespace-main-1-2 - Win32 Debug-------------------- Compiling... namespace-main-1-2.cpp namespace2.h(22) : error C2371: 'dup' : redefinition; different basic types namespace-main-1-2.cpp(34) : error C2228: left of '.setValue' must have class/struct/union type namespace-main-1-2.cpp(35) : error C2228: left of '.getValue' must have class/struct/union type namespace1.cpp namespace2.cpp namespace2.h(22) : error C2371: 'dup' : redefinition; different basic types Error executing cl.exe. namespace-main-1-2.exe - 4 error(s), 0 warning(s) */