views:

161

answers:

4

Hi, In my C++ project when I have to go for the inclusion (#include "myclass.h") of header files?? And when I have to go for forward declaration of the class (class CMyClass;) ?? Any suggestions regarding this are welcome.

+3  A: 

If you only need a pointer to the class and you don't need any knowledge about the class rather than its name, you can use the forward declaration.

ypnos
+2  A: 

As a rule try the forward decleration 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:

  1. Access a member or function of the class.
  2. Use pointer arithmatic.
  3. Use sizeof.
  4. Any RTTI information.
  5. new\delete copy etc.

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

Charles Beattie
+1  A: 

As a beginner, you should always #include header files when you need to use the types or functions they contain - do not try to "optimise" your build by forward declaring things - this is hardly ever necessary, even on large projects, provided the project is well architected.

The only time you absolutely need a forward declaration is in situations like this:

struct A {
   void f( B b );
};

struct B {
   void f( A a );
};

where each struct (or class) refers to the type of the other. In this case, you need a forward declaration of B to resolve the issue:

struct B;   // forward declaration

struct A {
   void f( B b );
};

struct B {
   void f( A a );
};
anon
+1  A: 

You should strive towards minimizing your #includes both in order to reduce compilation times but also to help with modularity and testability. As @ypnos says, class forwards are excellent when you only need pointers.

For some practical tips on how to reduce header dependencies, see e.g. this article.

Pontus Gagge