In my C++ project when do I have to use inclusion (#include "myclass.h"
) of header files? And when do I have to use forward declaration of the class (class CMyClass;
)?
You make the declarations in a header file, then use the #include directive in every . cpp file or other header file that requires that declaration. The #include directive inserts a copy of the header file directly into the . cpp file prior to compilation.
A header file is a file containing C declarations and macro definitions (see Macros) to be shared between several source files. You request the use of a header file in your program by including it, with the C preprocessing directive ' #include '. Header files serve two purposes.
Generally you would include forward declarations in a header file and then include that header file in the same way that iostream is included.
A forward declaration is much faster to parse than a whole header file that itself may include even more header files. Also, if you change something in the header file for class B, everything including that header will have to be recompiled.
As a rule try the forward declaration first. This will reduce compile times etc. If that doesn't compile go for the #include
. You have to go for the #include if you need to do any of the following:
new
/delete
, copy etc.(6,7,8,9 from @Mooing Duck)
They're are probably more but I haven't got my language law hat on today.
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