Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Header files inclusion / Forward declaration

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;)?

like image 952
liaK Avatar asked May 14 '10 08:05

liaK


People also ask

Can you use include in a header file?

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.

What is header file declaration?

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.

Where do you put forward declaration?

Generally you would include forward declarations in a header file and then include that header file in the same way that iostream is included.

Why forward-declare instead of include?

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.


1 Answers

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:

  1. Access a member or function of the class.
  2. Use pointer arithmetic.
  3. Use sizeof.
  4. Any RTTI information.
  5. new/delete, copy etc.
  6. Use it by value.
  7. Inherit from it.
  8. Have it as a member.
  9. Instance in a function.

(6,7,8,9 from @Mooing Duck)

They're are probably more but I haven't got my language law hat on today.

like image 184
Charles Beattie Avatar answered Oct 18 '22 13:10

Charles Beattie