Is it recommended to include each widget explicitly?
This might be about a practice, but I want to know how experts consider this issue.
Basically, all the base widgets are included together if I include a derived widget (for example, QFrame and QWidget are included together if I include QLabel)
And there is an example like below.
If included QWidget-derived widgets are used only in the findChild syntaxes,
this->findChild<QLineEdit*>("blahblah"); this->findChild<QLabel*>("blahblah2"); this->findChild<QPushButton*>("blahblah3");
They all can be replaced with
this->findChild<QWidget*>("blahblah"); this->findChild<QWidget*>("blahblah2"); this->findChild<QWidget*>("blahblah3");
In this case, including all the QLineEdit, QLabel, QPushButton is redundant.
On the contrary, if QLabel header was already included and if I have to find a QWidget like below,
There is no need to include QWidget because it was included already when QLabel was included.
As far as I know, there is no performance issue for this, but I want to know what would be a better practice.
The best practice recommends to include everything that you are using and only what you are using. Don't rely on indirect includes.
In your case, you are only using QWidget based classes and it's likely also the case where this code is called, so you already include QWidget in your class header, so including it again in the implementation would be redundant.
Hi @Aaron-Kim ,
@SGaist is correct. Include only what you need. I actually take this one step farther by using forward declarations in my header and use reference and pointer in variables. This has two effects:
- Keep header lightweight and fast to compile because it doesn't include tons of stuff.
- Keeps the work in the CPP file.
And, first and foremost, the usage depends on what your design intends to do.
@Buckwheat I do the same thing. Forward declarations and only including exactly what I need.
@Aaron-Kim Implicit declarations are bound to happen unfortunately. And they do indeed cause issues when they are changed in the code that is including them. I have had to deal with these problems numerous times.
Plan as best as you can and then just realize you will need to update your code to keep it current and building with new Qt's in the future. I've had projects that are only a few years old that have so many changes building them now would probably take me a day or 2 of time to "fix" the builds for newer Qt. In one case I was using a webkit that Qt didn't have any more. That one I just wrote off as a lost cause.
All that is a good reason for build servers and CI. That way you know right away when builds are broken by a dependency and can be fixed with minimal effort. Saving it all for later will definitely bite you. :)
Thanks for everyone for reply! I thought that forward declaration of QWidget-based headers is not a good practice, but I was wrong.