Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Need for Forward declaration



  • I am following the book , C++ GUI Programming with Qt4. In chapter 2 , there's a mention of forward declaration. For example

    #ifndef....
    #define ....
    
    #include <QDialog.h>
    
    class QCheckbox;
    class QPushButton;
    class QLineEdit;
    .......
    

    Can't these be used as follows;

    #include <QDialog.h>
    #include<QCheckbox>
    #include<QPushButton>
    #include<QLineEdit>
    
    

    I've always tried with header files and some of my programs have run successfully. So, can somebody differentiate between these two methods?


  • Lifetime Qt Champion

    @Swati777999 Forward declarations can help to break circular dependency: in header a you include header b and in header b you include header a -> circular dependency. You solve this using forward declarations, then you do not have to include the header file (you, of course, need to include it in cpp file, but this does not lead to circular dependency).

    Forward declarations also help to speed up compalation time, because you reduce the amount of includes in your header files. Each time you include a header file the preprocessor replaces the include statement with the content of the header file, but if the header file includes other header files then the amount of included text increases, which makes build times longer.



  • @Swati777999

    So the text says, for private variables, forward declaration of their classes is done as they are pointers and need to be accessed in the header files. Writing in terms of forward declaration speeds up the process of execution by the compiler.


  • Lifetime Qt Champion

    @Swati777999 Forward declarations can help to break circular dependency: in header a you include header b and in header b you include header a -> circular dependency. You solve this using forward declarations, then you do not have to include the header file (you, of course, need to include it in cpp file, but this does not lead to circular dependency).

    Forward declarations also help to speed up compalation time, because you reduce the amount of includes in your header files. Each time you include a header file the preprocessor replaces the include statement with the content of the header file, but if the header file includes other header files then the amount of included text increases, which makes build times longer.


Log in to reply