PDA

View Full Version : call a class



assismvla
24th May 2010, 00:31
what is the difference between declaring a class

this way:


#include <QDialog>
#include <QHash>


or, this way:


class QDialogButtonBox;
class QFile;
class QFtp;
class QLabel;
class QLineEdit;
class QTreeWidget;

dpatel
24th May 2010, 05:53
In first code snippet you are including the class by #include directive.

In second code snippet its forward declaration. You are just letting the compiler (or preprocessor am not sure which one) know that QFile is a class but I don't want to define it here or include it here. Then in you .cpp file you do and #include<QFile> which points to actual QFile class.

SixDegrees
24th May 2010, 08:07
As a practical matter, the first way includes the contents of the file it references, and the compiler has to grind through the contents of that file - which may be a significant amount of code. In the second case, the compiler only handles the single line of code. The end result is decreased compilation time if you use the second method.

Whether this is worthwhile is questionable. I typically include <Qt/GUI> in my headers, and despite the enormous amount of code this hauls in, my compilation times are still very quick, even on large projects. The total gain by using the second method would only be a matter of a few seconds, at best.

Also, note that in the second case you can only declare variables of the type specified; you have no access to their internal structure, because the compiler knows nothing about it. So it isn't as useful when you need to reference some internal class member.

Try it both ways. If you see a significant improvement in compilation speed with the second, and don't run up against it's limitations, go ahead and use it.

bender86
24th May 2010, 12:57
When you include the relative file, you are just "copying" the class definition, so the compiler knows everything about it. When you use the forward declaration, the compiler knows only that there is a class with that name. You can not declare a variable of that type, only a pointer or a reference (since the compiler does not know even how big is the class). Of course when you actually use that class (in the .cpp file) the compiler must know it, so you have to include the file there.

Forward declarations can be used for reduce compilation time, but also to reduce compiled files: if you have a header A.h which is included in B.h which is included in C.cpp, when you modify A.h you need to recompile C.cpp. If you used a forward declaration, no.
I have no idea if there are issues using forward declarations with Qt.

If you are worried about compiling speed, try precompiled headers (http://doc.trolltech.com/4.6/qmake-precompiledheaders.html).