C++: Namespace Essentials
In this C++ video tutorial, we covered a large amount of material. There are some things that we have not yet gone over about the more obscure aspects of namespaces, but we have covered the most essential material here.
Namespaces offer us a way to protect our code from naming clashes. For example, we could put our code on XoaX.net in a namespace called "XoaX" so that when our libraries are downloaded, they will not clash with your code or other third-party libraries that you are using.
For example, we might have a graphics library available for download with a function in it that draws a line from one point on the screen to another. To use this function to draw a line from (10, 100) to (200, 20), we would use the name XoaX along with the scope resolution operator (::) to differentiate our drawing function from others.
Of course, we may want to draw many lines. In this case, we would want to avoid typing XoaX every time. To make the function available without qualification, we can add a using-declaration like this:
In another case, we may want to use multiple functions and variables from the XoaX library. If there are not too many items, it may make sense to just use the using-declaration for each item as we did above. However, it may be easier to make a single using-directive like this:
In this example, the using-directive makes the entire namespace available without qualification. Here, we assume that the functions "DrawLine," "DrawCircle," and "DrawRectangle" are all defined in the namespace XoaX.
In addition to functions, we can put variables and other namespaces inside of a namespace. In fact, almost anything can be put into a namespace.
When nesting namespaces like this, we will often want to shorten the name. To do this we can create an alias for the namespace like this:
With this alias, we can refer to anything in the graphics namespace by using the much simpler "XG."