Saturday, November 7, 2009

What should I #include, where do I #include, not to have circular include error

Well, I was talking to Carl about what to include in my code and where to include them, not to have circular includes in my code, and I thought this could be useful to others too:

There are two things you should consider when you have lots of classes and header files in you project;
1- in header files, try not to include other header files, instead try forward declaration, or better to say, first use forward declaration, if not possible, use include.
2 - do all necessary includes in your ".C" and ".CPP" files instead.

How to "know" if you can use forward declaration? The answer is easy;
If all you have in your class header file, are references and pointers to a class, then only use forward declaration for that class.
On the other hand, if an instance of a class is created in the header file, or if you are inheriting a class from another, then the class header file must be included. To prevent this, try passing object by reference and pointers as much as possible...

For more detail, check the IRC conversation logs between me (fardad) and [Carl89] from [14:54] to [15:05] here , and also Carl's blog on this.

No comments:

Post a Comment