VCL includes TRect, TPoint, and TSize classes as well as Winsys classes with the same names. So, as we discuss in the accompanying article, you need a way to tell the compiler to differentiate between the two classes. The C++ namespace feature provides that means. Namespaces prevent the compiler from confusing two different classes having the same name.
When you add Winsys source files to your project in the accompanying article, you add an include to the Conditional Defines. Let me explain why. Each Winsys header contains a section that looks like this:
#if defined(BI_NAMESPACE)
namespace ClassLib {
#endif
This code tells the compiler, "If the symbol BI_NAMESPACE is defined, then place the following code in the ClassLib namespace." Now, what does that statement mean? Take the following code as an example:
TRect rect;This code obviously declares and instantiates a TRect object. But is it the VCL TRect class or the Winsys TRect class? At this point the compiler can't tell, so it will issue a compiler error stating Ambiguity between Windows::TRect and ClassLib::TRect. (The VCL TRect class is in the VCL Windows namespace.)
To avoid this problem, you need to declare the TRect variable using a namespace qualifier. Let's say you intend to use the Winsys version of TRect. In this case, you should write the code as follows:
ClassLib::TRect rect;Now the compiler knows which TRect class to use and goes merrily on its way compiling the unit.
However, you can take this process one step further and make the code even more simple. To do so, incorporate the using keyword as follows:
using ClassLib::TRect; TRect rect;This code tells the compiler, "From here on, when you see TRect, use the ClassLib version of TRect." You can always change back later to the VCL TRect by issuing another using statement. Such code prevents you from having to add the namespace qualifier to every TRect declaration in your code.
You'll notice in Listing A of the accompanying article, "Using OWL Classes in C++Builder," that no namespace qualifier is required for the TSystem and TUIMetric classes--those class names are unique to the Winsys classes and don't even exist in VCL. Since there's no chance of conflict, you don't need to qualify those declarations with namespaces. If you had a class of your own named TSystem, then you'd again need the namespace qualifier to differentiate the Winsys TSystem class from your own.
Kent Reisdorph is a editor of the C++Builder Developer's Journal as well as director of systems and services at TurboPower Software Company, and a member of TeamB, Borland's volunteer online support group. He's the author of Teach Yourself C++Builder in 21 Days and Teach Yourself C++Builder in 14 Days. You can contact Kent at editor@bridgespublishing.com.