When I write a C++ class I write includes in header only is specific cases. I prefer forward declaration and I believe that is best practice in C++. But Qt classes often have so many fields that are standard Qt classes that writing them all in forward declaration seems like not a very good idea. Is there some preferred way? Qt has huge documentation, so I think that it has answer to my question, but I just started reading it.
My rule is for a header file to include only those files that define functionality that is used by the header file in question.
Suppose you have pointers and references to some class Foo
in a header but the header never pokes into or instantiates one those objects. In this case, you don't need the definition of the class. All you need is a forward declaration.
On the other hand, a forward declaration does not suffice if you poke into an object of type Foo
, or if you have a data member or variable of type Foo
. Now you do need the full definition, so now it is time to #include
the header file that defines class Foo
. (Alternatively, if the use is in an inline function definition, you may want to rethink that inlining and put the implementation in a separate source file.)
A header file just says "what we can do". The cpp
file says "We can do it this way and that is our intention".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With