Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 821
Ferenc Deak Avatar asked May 29 '26 10:05

Ferenc Deak


1 Answers

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.

like image 191
TemplateRex Avatar answered Jun 01 '26 01:06

TemplateRex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!