In c++ are you allowed to split the definition of classes defined in the same header file across multiple source files? For instance if I have a file that defines the classes Quad2 and Quad3, can I define class Quad2 in a file called Quad2.cpp and Quad 3 in a file called Quad3.cpp but still have both in the same header file Quad.h?
Would this be considered illegal?
Yes, you can implement different classes from the same header file in different implementation files.
Header files are nothing more than textual content that gets injected into the source at the time of compilation. The compiler proper has absolutely no conception of a header. Headers are resolved in the preprocessor, before the compiler sees anything.
There is thus no requirement at all about which files a class's definition and implementation reside. The norms about what belongs in header files and what belongs in implementation files have everything to do with best-practice, and nothing to do with rules enforced by the compiler. I.e., you put class definitions in headers because that makes them easy to inject into both the implementation of that class and any code that wants to use the class.
Yes, perfectly legal. In fact, you can have Quad2A.cpp and Quad2B.cpp if you like to split the code into a smaller file (of course, it may not be of any benefit to do this).
One drawback with separating the sources, however, is that you make it harder for the compiler to inline functions that are small [or only used once]. Most compilers will only inline functions that are in the same compile unit. So if Quad3.cpp is using something from Quad2.cpp, then it's possible that it could be inlined if they are in the same file, but won't be if they are in separate files. However, this should not really be a deciding factor for your design - just mentioning it as one of the side-effects of "lets split this".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With