Why not forward-declare everything? (c++)

Started by
20 comments, last by Nemesis2k2 18 years, 10 months ago
Pre-compiled headers are useful for headers which aren't changing. Put windows headers, stl, boost, opengl etc in a pch. You'll get big speed ups just from doing that.

For you, every time you add a new class you'll have to recompile your whole project.

Also it is likely you will end up with headers which don't work on their own as you will come to rely upon the file with forward declarations in it. So for anyone to use your file they will have to include at least two headers in their cpp, the header with the classes or functions they need and the header with forward declarations. This just isn't friendly and increases coupling. Every time you make a change in the forward declaration file, which shouldn't affect the user, they will have to recompile. Not good. They won't thank you for it.

Make your headers simply self contained. Don't make them any more or less than they need to be to work. It takes little effort and in the long run is much better.
Advertisement
I've got a very complex and rigid header file system worked out, whereby I use a single template for every header and avoid all avoidable cyclic dependencies. Even in this system, I don't require the use of forward declarations, but I prefer to use them for everything I don't have to do a full include for. Anything that a class needs to only deal with pointers or references to, but doesn't need to interact with directly, I try and use a forward declaration for.

I prefer forward declarations where usable, because I'm dealing with a system that's very large, and involves many modules and packages. If I can use a forward declaration, it means there's a "weak link" between two modules. A full include implies a strong link. It's a distinction I find useful when looking at package dependencies, and assessing how changes to the public interface of a class might impact other modules. There's also the bonus that compile times are greatly reduced in my project through the use of forward declarations.

This topic is closed to new replies.

Advertisement