Question

I am wondering about the meaning of the following lines of code in a header file...

Firstly I have the standard using which makes a class from a namespace visible to my code

using mynamespace::myclass;

and then a forward declaration of the same class:

namespace mynamespace
{
    class myclass;
}

and finally the forward declaration of another class:

class myclass2;

What are the subtle differences for the programmer when "using" and when "forward declaring"? Which is more preferred when writing a header file?

Was it helpful?

Solution

Your first alternative is not valid. You can only give a using-declaration after a forward-declaration

namespace N { class C; } // OK, now we know that N::C exists

using N::C;              // OK, now we can type C whenever we mean N::C

A forward-declaration introduces a name, a using-declaration introduces an abbreviation of that name (i.e. you can leave out the namespace qualification).

Informal analogy with first and last names: a person will first be introduced, and only then will you get on a first name basis.

As a guideline: never put using-declarations into the global scope inside header files. This will introduce the shorthand into every translation unit that includes that header, and is likely to lead to name clashes.

OTHER TIPS

In order to forward-declare class, you don't need using directive, it is usually better just to use fully qualified name in the header:

namespace mynamespace
{
    class myclass;
}

class A{
    mynamespace::myclass* ptr;

};

Also, as jrok noted, you can't use using to bring the symbol to the current scope before the actual (forward) declaration of the symbol.

The only thing using does is make the specified symbol available in the current scope. It is unrelated to forward declarations.

Note that the specified symbol has to be declared already, so if you use both you'll have to forward declare first and then bring it into the current scope. Example:

namespace mynamespace {
    class myclass;
}

namespace this_header_namespace {
    using mynamespace::myclass;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top