Alex Rivera | Logout

Is it a good practice to always create a .cpp for each .h in a C++ project?

Asked 2009-10-29T17:28:07.737
10

Some classes, like exceptions or templates, only need the header file (.h), often there is no .cpp related to them.

I have seen some projects were (for some classes) there aren't any .cpp files associated to the headers files, perhaps because the implementation is so short that it is done directly in the .h, or maybe for other reasons, such as template classes, where it is mandatory to include the implementation in the header.

What is your opinion, if a class is too short, sould I avoid creating a .cpp file and writing the code directly on the header file ? If the code is written in the header file, should I include an empty .cpp so the files in the project remains consistent ?

Edit
Report

1 Answer

1

Please also see this question - the header files should only be for declarations.

If you have compilable code included in multiple places (from your comment: "sould I avoid creating a .cpp file and writing the code directly on the header file ?"), it will be compiled each time (although you might have pre-compiled headers) and the linker will resolve (or not) the bloated object code.

Just because the class definition is small does not mean it should be in the header file unless the definition is also the same as the declaration - e.g. a pure virtual class or a simple type as mentioned in the other answer.

answered 2009-10-29T17:45:10.620

Your Answer