Should I include header file or just forward declaration of a class?

In this post, I talked about the best practice to use forward declaration or include file for a class: only include header files for base class and value member class in the header of the class in question, let source file that uses this class include other header files. We said it is just best practice not necessary, i.e., you can include all header files in source files, just remember to put them before the inclusion of this header file.

However, this best practice becomes a necessary rule for classes in Qt projects. Now you must include the headers instead of using forward declarations for base class and classes of value members in the header file. Why? This is because Qt creator creates a moc file automatically, in which the header file is included at the first line. This file is not supposed to be edited by you. If you use forward declarations, the moc file won’t compile(“uses undefined class xxxx”). So, although you can try to compile your own source files by including needed headers in them, you cannot successfully build your project without applying this rule if you do not(and should not) edit the auto-generated moc file.

 

If you like my content, please consider buying me a coffee. Buy me a coffeeBuy me a coffee Thank you for your support!
Posted in

Leave a Reply