FAQ 15.08 Can namespaces break code?

graphics/new_icon.gif

Namespaces can cause code to suddenly not compile without changes by the programmer. The easiest way this can occur is discussed in FAQ 15.09, but that situation involves the conscious use of using directives, so there shouldn't have been any surprises at the consequences. Here's an example that's a little more insidious.

Start with a header that declares a namespace MySubsystem and a class Fred in that namespace. For example, the following might be in file MySubsystem.hpp:

 #ifndef MY_SUBSYSTEM_HPP #define MY_SUBSYSTEM_HPP namespace MySubsystem {   class Fred { }; } #endif 

Now suppose some user code creates a normal function f() that takes a parameter of type MySubsystem::Fred:

 #include "MySubsystem.hpp" void f(MySubsystem::Fred& x) throw(); int main() {   MySubsystem::Fred x;   f(x);  // Uses the global f() that takes          // MySubsystem::Fred& as a parameter } 

Now suppose a revision of MySubsystem.hpp adds a function f(Fred& x) to namespace MySubsystem:

 #ifndef MY_SUBSYSTEM_HPP #define MY_SUBSYSTEM_HPP // This is a revision of the original header namespace MySubsystem {   class Fred { };   void f(Fred& x) throw(); } #endif 

Suddenly, there is ambiguity as to which f(x) is needed, and the code will not compile.

There are even more exotic examples, but the main point is that there are several ways ambiguity can creep in, and the programmer has to resolve the conflicts manually. This is not a severe problem because the compiler flags it and it is relatively easy to fix.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net