6

I am reading book about using Qt5 (author Max Schlee), and I noticed that some examples have declared existing Qt class in the header file, for example like this:

class QProgressBar;

So, my question – why don't we just include the header file QProgressBar without declaring class QProgressBar; in our header file?

Ilya
  • 4,583
  • 4
  • 26
  • 51
zh_
  • 95
  • 8
  • The main reason for not wanting to do that is that you should be using child objects/widgets by value, and then you have to include relevant headers anyway - you can't use forward-declared classes. Most of Qt examples use pointers to child objects and child widgets with abandon, and completely unnecessarily... – Kuba hasn't forgotten Monica Mar 11 '16 at 22:22

1 Answers1

8

It's not about Qt, it's c++.

It's called forward declaration.

Basically in the .h you just say that QProgressbar is a class and do not complain about the fact that it's not defined. Then in the .cpp file you put the header, so that at compile time, the compiler will have everything well defined.

This can save compile time, as #include force the compiler to open more files and process more input.

This can also save on unnecessary recompilation. #include can force your code to be recompiled more often, due to unrelated changes in the header.

Of course on large projects you can have drawbacks.

You can find more HERE.

Community
  • 1
  • 1
bibi
  • 3,671
  • 5
  • 34
  • 50