Tuesday, 5 January 2010

Classes in H files

While working on my homebrew game, I noticed a thing I'd never really considered before. I've been thinking about compile times and link times recently and this one clicked as a fresh thought.

When you include your classes in header files, you automatically add complexity in the project through the header includes that are necessary to compile the class, and the link time complexity of the methods of that class being linked if used.

We know that the linker doesn't try to link methods that aren't called, as we've probably quite often seen classes written without their implementations as half done cases. So what's wrong with adding class methods? It's quite simple: all the methods that are implemented in a class are subject to being possibly linked at some point and therefore become one more item in the linkers list of suspects.

That's for every class you write.

There's no simple way of stopping the linker from giving access to class methods. There is a simple solution if you use global functions. You can use static global functions for your implementation details.

This thinking lead me to go half way on my game with my change from putting classes in headers to putting them as worker objects in the source files, and then operating them with global functions where possible. I think there might be a way to remove the class symbols from the objects, but until I find it, at least I'm ready, and thinking good for large-scale development. The class in question was a game level class that contains the stuff for managing the game level. The overall game needs to know very little about the class, just that it's running, and that it can be managed (transitioned) and saved (serialised). This simple interface is quite different from the internal workings and therefore the header would have had to include all sorts of unnecessary information. I think this is proper data-hiding and encapsulation rather than the C++ textbook version.

I'll keep tabs on this and see how it goes.
Post a Comment