Search code examples
c++headernamespacesforward-declarationusing-declaration

Forward Definitions and namespace using


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?


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.