Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include in header or cpp - what is preferred in Qt

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.

like image 554
Hate Avatar asked Jan 14 '23 14:01

Hate


2 Answers

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.)

like image 113
David Hammen Avatar answered Jan 29 '23 01:01

David Hammen


A header file just says "what we can do". The cpp file says "We can do it this way and that is our intention".

like image 21
Ed Heal Avatar answered Jan 29 '23 01:01

Ed Heal