using Declarations in C++

Now that we have a complete understanding of using directives in C++, lets take a look at using declarations. Using declarations are easier to understand, especially now that we’ve gained an understanding of other concepts such as scope, and namespaces.

using declarations serve a similar purpose than using directives: we want to use something that is within a namespace without having to write the fully qualified name every time we want to use it. A using declaration looks like this:

using nsName::entityName;

As you can see, all you do is refer to an entity using its fully qualified name. After this, you can use that entity by calling it by its simple name.

How using Declarations Work

As with using directives, we need to understand what happens when we use a using declaration. We already know that a using directive works by placing everything withing the referred namespace into the closest namespace shared by the referred namespace and the curent scope. using declarations, however, work by placing the referred entity into the current scope. This distinction is important because knowing it will help us determine where to place our using declarations.

A Rule of Thumb

A good rule of thumb when working in C++ is to declare variables close to where they will be used. For example, if a variable will be used in an function, then you should declare it in that function. If it will be used in an if statement, then declare it in that if statement. We can apply the same rule to using declarations because they place the referred entity into the current scope.

This time I won’t go into much detail, because I think that understanding how using declarations work is very easy. However, I do want to show an example of when, and why using declarations coule be problematic. Consider the following code:

namespace myNs {
  int number = 0;

int main() {
  int number = 1;
  using myNs::number;
  return 0;

If you tried to compile this code, you would get an error. The problem is that when the using declaration tries to move myNs::number into the scope of the main function, it finds that there is already a variable in there that has been declared with the same name.

I want to end this short entry with a few links where you can read some more about real-world instances where using directives and declarations come into play: