PDA

View Full Version : Why forward declaration ?



probine
26th January 2007, 00:50
I am wondering:
-------------------------------------------------------

In a ".h" header file I can declare something like:

class QTextBrowser;

and in the respective ".cpp" class I will add this:

#include <QTextBrowser>

----------------------------------------------------------

I can also declare the "#include" in the header file (I know it).


Question:

Why is it better to "#include" a class in a .cpp instead of including it in the .h ?
Why it is not better ?

Methedrine
26th January 2007, 01:04
@Mods: maybe this should be moved to the general c++ forum?

@OP:
Rule of thumb: If you can use a forward declaration, use it!

This is because of the way includes work. If you include a file in a header file, it's definitions are available in all other files which include said header file. So, if you have the following piece of code, how should the compiler decide which string class to use?



=========
header1.h
=========

#include <string>
using namespace std;

=========
header2.h
=========

#include <header1.h>

namespace myns
{
class string
{
//... implementation
};
}

using namespace std;

==========
source.cpp
==========

int main(int argc, char** argv)
{
// which string shall the compiler use? std::string or myns::string?
string x = "Hello World!";
cout << x:
return 0;
}


Using forward declaration also improves the time used to build your application as less object files are linked to each other (if I recall correctly right now, had a few beers tonight).

Chicken Blood Machine
26th January 2007, 17:36
By including header files that you don't need, you are giving unecessary work to the preprocessor and hence slowing down your compile time.

Any data type that you declare either by reference or by pointer does not need to have its header included. You can forward declare it and should always forward declare it.

@Methedrine Never use 'using namespace xxx' in a header file. It is very dangerous!

Methedrine
26th January 2007, 18:22
@Methedrine Never use 'using namespace xxx' in a header file. It is very dangerous!

Indeed, and I thought my example code would outline that problem nicely, but yeah I also spotted the problem with my example: Instead of "using namespace myns" in header2.h I wrote using namespace std again ;-) that of course leads to std::string being used.