0

I am new to C++ so please be kind. I was wondering if we really have to put classes in headers files (.h) . I know it looks better and is more efficient to separate the definition with the implementation but is there another benefit of doing this such as faster compilation or something like that?

Anything would help, thanks!

Yawn
  • 71
  • 7
  • 5
    You don't HAVE to, but it does help ORGANIZE your code better. But it is *especially* important to use if you need to share your classes across multiple translation units, since each unit must use the same class definitions (See [One Definition Rule](https://en.cppreference.com/w/cpp/language/definition) and [Don't Repeat Yourself](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself)). – Remy Lebeau Feb 19 '21 at 17:32
  • 1
    Sit tight and wait for [c++20 modules](https://www.modernescpp.com/index.php/c-20-modules), first step to remove annoying headers (inherited from C). Still we have to live with them for couple years. Anyway good IDE minimizes this problem (CLion does this nicely). – Marek R Feb 19 '21 at 17:50

2 Answers2

1

Actually you don't have to. However using header files has following benefits:

  1. Enables you to find your classes easier by choosing your desired file rather than time consuming scrolls.
  2. Your code is easy to maintain, meaning that developing process is easier and faster in the future.
  3. It potentially can reduce compiling time, because instead of loading whole code it loads the required ones.
Saeed All Gharaee
  • 1,546
  • 1
  • 14
  • 27
  • Your welcome.for more info checkout this: https://stackoverflow.com/questions/193864/pros-cons-of-putting-all-code-in-header-files-in-c – Saeed All Gharaee Feb 19 '21 at 17:47
  • `It reduces compiling time` what? This is main source of long build times. Most developers do not care to maintain headers carefully (forward declarations). – Marek R Feb 19 '21 at 17:53
  • @MarekR • Probably should have been stated as "*Potentially* can reduce compiling time, assuming the dependency graph is well maintained, and with conscientious discipline and forethought." – Eljay Feb 19 '21 at 18:00
1

All classes must be fully defined in every translation unit that uses objects of that type. You must make sure that these are all identical, or else the behavior of the program is undefined. And when you make some change to any of the definitions, you must change all others accordingly.

Someone came up with the idea of putting all class definitions in a single file, and using the preprocessor to copy+paste it everywhere we need those classes. This is the #include "file" directive which basically replaces this line with the contents of file.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93