Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

this is my first time here. I\'m a physics grad student and I\'ve recently found

ID: 655581 • Letter: T

Question

this is my first time here.

I'm a physics grad student and I've recently found a research group to work with. We study statistical mechanics using computer models, so there is a significant programming aspect to it.

My first job has been to take the old data analysis code (written in java) and clean it up in c++. The guy before me who wrote the original program used the traditional physics method of using an enormous amount of spaghetti code and shoving it all in a constructor. This irked me quite a bit, so I divided it up into separate classes and now it has a reasonable class structure.

In the past, whenever we had defined a class we would put its definitions and its methods in a header function, then to use it we would just include it. I know this breaks the rules of how to use .h and .cpp files, but is there any reason other than code etiquette to compile and link a class object rather than include it?

Sorry for the long question.

Explanation / Answer

The idea of headers is that we separate the public interface (i.e. declarations) from internal implementation details (i.e. the actual method bodies). This split has all kinds of advantages:

There's a helper function I need? Let's just put it into the .cpp file, and outside code cannot see it. I can also do things like using std without interfering with other code.
We are stuck in a C mindset and want to use a macro? Declare it in the .cpp file to avoid polluting outside code.
There is a bug in a method? After fixing it, we only need to recompile that single .cpp file and re-link the application. This is much faster than recompiling everything.
Related to that: header files are often included multiple times, and are therefore recompiled again and again