Header files inclusion / Forward declaration

liaK picture liaK · May 14, 2010 · Viewed 20.3k times · Source

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

Answer

Charles Beattie picture Charles Beattie · May 14, 2010

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.